如何动态地建立文本链接? - JQuery初学者

时间:2011-11-17 21:16:12

标签: javascript jquery

我在页面上有很多这些:

<div class="item" id="555">
  <div class="wrapper>
    <p>Make Link One</p>
  </div>
  <p class="action">Make Link Two</p>
</div>

如何基于id 555动态制作2个文本链接?即。它们都应该是http://555

的链接

有一个独特的业务要求,这就是它们不仅仅是正常的hrefs的原因。

4 个答案:

答案 0 :(得分:1)

您可以将click事件处理程序绑定到包含div,该div使用它自己的ID来重定向用户:

$('.item').on('click', function () {
    window.location = 'http://' + this.id;
});

如果容器元素中有其他内容不应该触发重定向,那么您可以绑定到容器内的<p>元素:

$('.item').on('click', 'p', function () {
    window.location = 'http://' + $(this).parents('.item:first')[0].id;
});

顺便说一句,ID不应该以数字开头。以下是ID正确语法的链接:What are valid values for the id attribute in HTML?

请注意,.on()是jQuery 1.7中的新功能。在第一个示例中,替换了折旧的.bind(),在第二个示例中,它替换了折旧的.delegate()

答案 1 :(得分:1)

$('p').each(function(){
    var $this = $(this);
    var href = $this.parents('.item:first')[0].id;
    $this.wrap('<a href=http://"' + href + '">');
});

.each遍历找到的p元素。然后,它会查找父类{i} .item$this.parents('.item:first'))以获取ID。 [0]部分将jQuery对象转换为标准DOM元素,以便我们可以轻松地从该元素中获取id属性(您也可以使用$this.parents('.item:first').attr('id')来坚持使用纯jQuery) 。最后,我们将p打包在一个带有正确href

的锚标记中

答案 2 :(得分:1)

$(document).ready(function(){

  $(".item p").each(function(){
  var t1 = $(this).text();
  var linkid = $(this).parents('.item:first').attr("id");


  $(this).parent().append('<a href="http://' + linkid + '">' + t1 + '</a>');
  $(this).remove();

  });


});

答案 3 :(得分:0)

我会这样做,假设您希望它适用于每个p,它是item类元素的子元素:

$(function(){
    $('.item p').each(function(){
        var $this = $(this);
        $this.contents().wrap($('<a>', { href: $this.closest('.item').attr('id') }));
    });
});