问题
Based on this I am trying to add the click event handler to an array of objects by writing this:
function addEventHandler(array, type, func) {
var len = array.length;
for (var i = 0; i < len; i++) {
array[i].bind(type, func);
}
}
sections = $('#sponsorship > div .section')
addEventHandler(sections, 'click', function() {
console.log(this);
});
However, I am getting the error message:
array[i].bind is not a function
Can I only use actual selectors on a bind method? Any suggestions?
回答1:
You may need to convert your element into a jQuery object.
$(array[i]).bind
回答2:
try this
function addEventHandler(array, type, func) {
var len = array.length;
for (var i = 0; i < len; i++) {
array.eq(i).bind(type, func);
}
}
回答3:
The error message you are getting is exactly what you'd get by trying to run jQuery functions on non-jQuery objects. You can easily fix this by using the index of your for loop to access the jQuery objects in the array
variable:
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);
});
Changing array[i].bind(type, func);
to array.eq(i).bind(type, func);
accesses the jQuery object rather than a regular JS object which will remove the error you're getting.
Here is a jsfiddle of the above change to your code: http://jsfiddle.net/jfUpB/1/
回答4:
I'd replace the for(int...) by jQuery's $.each function as you'd be dealing with the item of the array and not the trying to retrieve the item by index. Also, to use any jQuery function, your object inside the array should be a jQuery object, so I'd do this:
function addEventHandler(array, type, func) {
var len = array.length;
$(array).each(function(index, item) {
$(item).bind(type, func);
});
}
回答5:
$('#sponsorship > div .section').click(function (event) {
console.log(event.target);
});
or
$('#sponsorship > div .section').each(function(index,item) {
$(item).click(function (event) {
console.log(event.target);
});
});
Whats wrong with this ?
回答6:
.each()
is performance heavy, and considered 'lazy' even by jQuery's standards.
来源:https://stackoverflow.com/questions/8273202/jquery-add-an-event-handler-to-objects-in-an-array