为什么jquery.bind()在这种情况下不起作用?

为什么jquery.bind()在这种情况下不起作用?,jquery,bind,Jquery,Bind,我使用jquery的bind方法有什么问题 工作 var Element = htmlBody.find('tag'); $(Element ).bind('DOMSubtreeModified', function(event) { console.log(Element[0]); //code come here }); var obj = {}; var tags = ['tag1', 'tag2']; for (index in tags) { obj[inde

我使用jquery的bind方法有什么问题

工作

var Element = htmlBody.find('tag');
$(Element ).bind('DOMSubtreeModified', function(event) {
    console.log(Element[0]);
    //code come here
});
var obj = {};
var tags = ['tag1', 'tag2'];
for (index in tags) {
    obj[index] = htmlBody.find(tags[index]);
    $(obj[index]).bind('DOMSubtreeModified', function(event) {
        console.log(obj[index][0]);
        //  code doe not come here
    });  
}
不工作

var Element = htmlBody.find('tag');
$(Element ).bind('DOMSubtreeModified', function(event) {
    console.log(Element[0]);
    //code come here
});
var obj = {};
var tags = ['tag1', 'tag2'];
for (index in tags) {
    obj[index] = htmlBody.find(tags[index]);
    $(obj[index]).bind('DOMSubtreeModified', function(event) {
        console.log(obj[index][0]);
        //  code doe not come here
    });  
}
请尝试以下操作:

var obj = {};
var tags = ['tag1', 'tag2'];
$.each(tags, function(idx, item) {
    obj[idx] = htmlBody.find(tags[idx]);
    $(obj[index]).bind('DOMSubtreeModified', function(event) {
        console.log(item);
    });  
});

建议使用
on
函数而不是
bind()
。您还需要使用
for
循环遍历元素

var obj = {};
var tags = ['tag1', 'tag2'];
for (var i = 0; i < tags.length;i++) {
    obj[i] = htmlBody.find(tags[i]); //not exactly sure what htmlBody.find does
    var item = obj[i][0];
    $(obj[i]).('DOMSubtreeModified', function(event) {
        console.log(item);
    });  
}
var obj={};
变量标记=['tag1','tag2'];
对于(var i=0;i
您不应将
用于。。。在
中迭代数组。在您的情况下,您可能遇到了它的
length
属性。请改用计数器变量。请尝试使用$。不推荐使用临时变量
domsubtreemedited
进行each()/迭代。。单击此处了解更多信息:除了代码中的一些特性(我假设是为了演示目的而截断的版本)之外,它的工作方式非常复杂:另一个问题是在中的闭包变量
I
的Callbackware中错误地使用闭包变量
index
callback@ArunPJohny谢谢从jQuery1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。对于早期版本,.bind()方法用于将事件处理程序直接附加到元素。