jquery为数组中的对象添加事件处理程序
基于此,我试图通过编写以下内容将click事件处理程序添加到对象数组:
function addEventHandler(array, type, func) { var len = array.length; for (var i = 0; i div .section') addEventHandler(sections, 'click', function() { console.log(this); });
但是,我收到错误消息:
array[i].bind is not a function
我只能在绑定方法上使用实际选择器吗? 有什么建议?
您可能需要将元素转换为jQuery对象。
$(array[i]).bind
试试这个
function addEventHandler(array, type, func) { var len = array.length; for (var i = 0; i < len; i++) { array.eq(i).bind(type, func); } }
您获得的错误消息正是您尝试在非jQuery对象上运行jQuery函数所获得的。 您可以通过使用for循环的索引来访问array
变量中的jQuery对象,从而轻松解决此问题:
function addEventHandler(array, type, func) { var len = array.length; for (var i = 0; i < len; i++) { array.eq(i).bind(type, func); } } sections = $('#sponsorship > div .section') addEventHandler(sections, 'click', function() { console.log(this); });
更改array[i].bind(type, func);
to array.eq(i).bind(type, func);
访问jQuery对象而不是常规的JS对象,这将删除你得到的错误。
以下是您的代码的上述更改: http : //jsfiddle.net/jfUpB/1/
我将用jQuery的$ .each函数替换for(int …),因为你要处理数组的项而不是尝试按索引检索项。 另外,要使用任何jQuery函数,数组中的对象应该是一个jQuery对象,所以我这样做:
function addEventHandler(array, type, func) { var len = array.length; $(array).each(function(index, item) { $(item).bind(type, func); }); }
$('#sponsorship > div .section').click(function (event) { console.log(event.target); });
要么
$('#sponsorship > div .section').each(function(index,item) { $(item).click(function (event) { console.log(event.target); }); });
这有什么不对吗?
.each()
性能很重,甚至被jQuery的标准认为是“懒惰的”。