开发者

jQuery: multiple selectors - unbind click from all selectors with $(this)?

quick and probably dumb question. I have the following situation: I select multiple elements and bind a click handler to them. After they are clicked I want to remove the handler and unbind the click from all of them. $(this) always refers to the element that is actually clicked, so $(this) only removes the click handler from the element that is clicked - not from all selectors I bind the event to.

$(modal + ' .modal-close, ' + modal + ' a.cancel_link, ' + modal + ' .okBtn').bind('click', function(e) {
        e.preventDefault();
        ...
        //$(this).unbind('click');
        $(modal + ' .modal-close, ' + modal + ' a.cancel_link, ' + modal + ' .okBtn').unbind('click');
});

The weird question is. Is there a better way to this or do I have to repeat all selectors within the function to unbind the click from all selectors? I know I could declare a variable before, but i开发者_运维问答s there anything like $(this-all) :)


You can capture the initial jQuery object in the closure:

var $all = $(modal + ' .modal-close, ' + modal + ' a.cancel_link, '
    + modal + ' .okBtn');
$all.click(function(e) {
    e.preventDefault();
    // ...
    $all.unbind("click");
});


Declaring a variable, as you said, is probably your best bet.

$(this-all) would not make sense in a lot of situations, because the click event doesn't know the particular selector you used when you bound that event, it just knows the element and the function to execute.

Note that there is a neater way of doing what you're doing. Rather than building a selector piece by piece, you can use the .find() method to find ancestors of the selected element:

var $modal = $(modal); // assuming `modal` is a string
var $elems = $modal.find('.modal-close, a.cancel_link, .okBtn'); // hyphens, underscores, and camelCase -- oh my!
$elems.click(...);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜