使用document.getElementsByTagName('div')
时,您将获得一个div节点数组,它可以在循环中将不同的事件分配给不同的div。如何将不同的事件添加到不同的div
我该如何做到这一点与jQuery?
使用document.getElementsByTagName('div')
时,您将获得一个div节点数组,它可以在循环中将不同的事件分配给不同的div。如何将不同的事件添加到不同的div
我该如何做到这一点与jQuery?
你可以做同样的jQuery的:
$('div').each(function() {
if ($(this).attr('id') == '1')
$(this).click(function() { // handler for first div });
if ($(this).attr('id') == '2')
$(this).click(function() { // handler for second div });\
...
});
只需添加名字到jQuery的选择...
$(“标签名称 - 这里”)
然后可以使用.each
,但是对于性能我更喜欢使用好的旧Javascript的循环。
这可能会帮助:http://api.jquery.com/each/ & http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html
$('div')
这将创建的DIV的一个jQuery集合Docs
要做到这一点jQuery的使用:
$("div").each(function() {
// 'this' is the div
});
这是相同:
var divs = document.getElementsByTagName('div'),
i,
len,
div;
for (i = 0, len = divs.length; i < len; i++) {
div = divs[i];
}
var divs = jQuery('div');
divs.each(function(){
$(this).DoSomeThing();
// $(this) refers to a div
});