开发者

Get selector in event handler

I answered this question with this jQuery code:

$('input开发者_Go百科[type="checkbox"][name$="chkSelect"]').click(function() {
  $('input[type="checkbox"][name$="chkSelect"]').not(this).prop("checked", false);
});

... and it got me thinking: there must be a way to avoid duplicating the selector in the event handler.

I tried $(this).selector but that just returns an empty string. Here's a demo.

Is there a way to get the selector text in the event handler?


$(this).selector does not work because you create a new jQuery object and pass a DOM element, not a selector.

If you only want to avoid repeating the selector, you can cache the elements beforehand (which is better anyway):

var $elements = $('input[type="checkbox"][name$="chkSelect"]');
$elements.click(function() {
    $elements.not(this).prop("checked", false);
});

But I don't think there is a way to get the selector inside the event handler. The only reference you have to the selected elements is the corresponding DOM element (through this). But you cannot "reverse engineer" the selector from that.


You can always do:

for(var i in arr){
  $(arr[i]).bind('click', {'selector': arr[i]}, function(event){
    console.log(event.data.selector);
  });
}


This guys seems to have done it. How do I get a jQuery selector's expression as text? - see Pim Jager's answer


$('div').click(function() {
    alert($(this)[0].nodeName);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜