2010-05-04 49 views
0

这个问题是继续How to get attributes of container in jQuery,我在我的网页上有不同的容器,他们都有<div id = "some values">。现在我怎样才能为每个组件分别获取属性值?如何获取jQuery中网页上每个容器的属性值?

有没有什么办法可以知道哪个属性id属于哪个容器div?

目前我使用:

var id = $('.promotion').attr('id'); 

但是,如果我有网页上有多个宣传部件,以及一切具有相同的div属性作为ID不是我怎么能与这个特定的属性ID属于这个特定的容器?

更新:我有一个被称为对当前页面上的,因此,如果我使用上面提到的代码比将它并不总是返回我的第一场比赛中的id在div,绝不每个容器的功能去其他divs,所以我会永远得到相同的价值为第一个容器的id?如果是这样的话,那么工作是什么?

var id = $('.promotion').this.attr('id'); 

var id = $('.promotion').$this.attr('id'); 

var id = this.$('.promotion').attr('id'); 

如何知道属性值是否为当前容器,那么应​​该如何正确使用它来获取此信息?

希望这个问题很明确。

回答

1

可以遍历和处理每个div都单独

$(".promotion").each(function() { 
    var id = this.id; // 'this' is the html element, not the jquery object 
}); 

更新

function myfunc() { 
    alert(this); 
} 

// inside myfunc, this will be the window 
myfunc(); 
// call (also: apply()) changes "this" to be the first argument 
myfunc.call(document.getElementById("someid")); 

jQuery使用this指代正在处理的当前元素。在将是目标元素的事件中。在.each它是集合中的当前元素。

考虑:

$(".promotion").click(function() { 
    alert(this); // will alert with the div that was clicked 
}); 

在jQuery中您可以使用$(element)包装任何HTML元素具有JQuery Object。所以,当this就像在本例中的HTML元素上面,你可以使用$(this)

$(".promotion").click(function() { 
    alert($(this).attr("id")); // will alert with the div that was clicked 
}); 

玩弄在这里:http://jsbin.com/okuri3/edit

更多this

+1

但是你可以使用$(this)来得到它理所当然的jQuery对象。 +1 – Hober 2010-05-04 21:34:58

+0

请检查我的更新,因为它可能会进一步澄清我正在尝试完成的事情。 – Rachel 2010-05-04 21:36:14

+0

@Hober:是的,如果你需要的话。 @Rachel:你可以发布更多的代码吗?我不明白你想要从你的更新中做什么。如果你已经有了一个为每个元素调用的函数,为什么你不能只调用'element.id'或'$(element).attr(“id”)'来获得传入的特定元素的id的功能? – Joel 2010-05-04 21:40:12