在事件处理程序中获取选择 [英] Get selector in event handler
问题描述
我用这个jQuery代码回答了这个问题:
I answered this question with this jQuery code:
$('input[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.
我尝试了 $(this).selector
但这只返回一个空字符串。 这是一个演示。
I tried $(this).selector
but that just returns an empty string. Here's a demo.
有没有办法在事件处理程序中获取选择器文本?
推荐答案
$(this).selector
不起作用,因为你创建了一个 new jQuery对象并传递了一个DOM元素,而不是一个选择器。
$(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);
});
但我不认为有办法让选择 >事件处理程序。您对所选元素的唯一引用是相应的DOM元素(通过 this
)。但你不能从那里反向工程选择器。
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.
这篇关于在事件处理程序中获取选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!