我在一个页面上有一堆这样的东西:
<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
有一个独特的业务需求,这就是为什么它们一开始就不仅仅是正常的href。
您只需将点击事件处理程序绑定到包含的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正确语法的链接:HTML中id属性的有效值是什么?
请注意,.on()
在jQuery 1.7中是新的。在第一个示例中替换已折旧的.bind()
,在第二个示例中它替换已折旧.delegate()
。
$('p').each(function(){
var $this = $(this);
var href = $this.parents('.item:first')[0].id;
$this.wrap('<a href=http://"' + href + '">');
});
CCD_ 6循环通过所找到的CCD_。然后,它通过类.item
($this.parents('.item:first')
(查找父iwth来获取id。[0]
部分将jQuery对象变成一个标准DOM元素,这样我们就可以很容易地从该元素中获取id
属性(您也可以使用$this.parents('.item:first').attr('id')
来坚持纯jQuery(。最后,我们用正确的href
将p
封装在锚标签中。
$(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();
});
});
我会这样做,假设您希望它应用于每个p
,它是具有item
类的元素的子元素:
$(function(){
$('.item p').each(function(){
var $this = $(this);
$this.contents().wrap($('<a>', { href: $this.closest('.item').attr('id') }));
});
});