Odd behavior when binding a click to two elements in jQuery
I have two images with the title "Show Options". I want to assign a click event to both of them and I want the clicks to print different statements.
console.log($('img[title*=\"Show\"]'));
$('img[title*=\"Show\"]').each(function(index, value){
switch(index){
case 0:
console.log('object');
$(this).live('click', function(e) {
console.log('object clicked');
});
break;
case 1:
console.log('record');
$(this).live('click', function(e) {
console.log('record clicked');
});
break;
}
});
ODD BEHAVIOR
object
andrecord
are 开发者_运维百科printed so I know there are 2 elements.- When I click on the image that is associated with object,
record
is printed. - When I click on the image that is associated with record, nothing is printed.
I am not sure how I can resolve this.
The purpose of the .live
method is to allow you to specify event handlers on DOM objects that may change, or do not yet exist. This works because in fact no handler is attached at all. Instead, a pre-existing handler at the root of the document looks through all of the selectors registered with .live()
to determine if any of them is a match.
In your example, you are passing in a DOM object directly, and not a jQuery selector. So, what's probably happening (although, I'm not sure) is that it's trying to attach live events to selectors created by stringifying the DOM objects, which can lead to strange, unexpected results.
If you're trying to attach events to a single DOM object that will not change, just use the .bind()
function.
If you really needed to use live, you could restructure the code so that you specify selectors that match the elements. For example:
var selector = 'img[title*=\"Show\"]';
$(selector).each(function(index, value){
switch(index){
case 0:
console.log('object');
$(selector+":eq(0)").live('click', function(e) {
console.log('object clicked');
});
break;
case 1:
console.log('record');
$(selector+":eq(1)").live('click', function(e) {
console.log('record clicked');
});
break;
}
});
In general, this is a very bad pattern, and there are much more eloquent ways to do things. However, it is in theory possible to make this pattern work.
精彩评论