【发布时间】:2012-02-21 17:18:25
【问题描述】:
调用自定义插件时,如何获取当前选择器字符串?
$('my_selector p').my_plugin();
想在我的脚本中输出my_selector p。我怎样才能访问这个字符串?
【问题讨论】:
标签: jquery string jquery-selectors
调用自定义插件时,如何获取当前选择器字符串?
$('my_selector p').my_plugin();
想在我的脚本中输出my_selector p。我怎样才能访问这个字符串?
【问题讨论】:
标签: jquery string jquery-selectors
【讨论】:
后选择器弃用 v. 1.7:
如果您只是将 id 和类作为选择器处理,您可以使用以下内容:
var selector = (typeof($(this).attr('id')) !== 'undefined' || $(this).attr('id') !== null) ? '#' + $(this).attr('id') : '.' + $(this).attr('class');
有一些更简洁的方法,但自从 .selector 因 1.7 以来浏览器之间的不一致而被删除后,这一直是我的首选。
【讨论】:
.unique-class-123 p strong.help,它只会返回.help
(typeof($(this).attr('id')) !== 'undefined' && $(this).attr('id') !== null),例如如果选择器是“未定义”但“非空”并且ID为空,它将返回#undefined
已弃用,官方建议是在函数调用中添加选择器作为参数:https://api.jquery.com/selector/
需要在其插件中使用选择器字符串的插件可以将其作为方法的参数。例如,“foo”插件可以写成
$.fn.foo = function( selector, options ) { /* plugin code goes here */ };
使用插件的人会写
$( "div.bar" ).foo( "div.bar", {dog: "bark"} );
冗余,是的,但它总是可靠的。
【讨论】:
jQuery.fn.getSelector = function() {
return this.data('selector');
};
【讨论】:
undefined (jQuery v2.2.4)。
最好的解决办法是
function mySelector(selector) {
return $.extend($(selector),{"selector":selector});
}
这会像 $() 那样返回经典的 jquery 对象
mySelector(".myClass")
这会返回选择器的字符串
mySelector(".myClass").selector
【讨论】:
selector 已弃用,我使用
index = document.getElementById('category').value
select = $("#category option[value=#{index}]")[0].innerHTML
只有两行代码
或者如果你的线路真的很便宜
select = $("#category option[value=#{document.getElementById('category').value}]")[0].innerHTML
【讨论】:
扩展到 kevinmicke 的 answer :您可以在传递回调函数的事件对象中获取选择器。
event.handleObj.selector
您将在 e.handleObj.selector
中获得选择器字符串 $( '.container' )
.on('change', 'select.mySelector', function (e) {
console.log(JSON.stringify(e));
$('.selector').text(e.handleObj.selector);
$('.value').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<select class="mySelector">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<h3>Your Selector: <span class="selector"></span></h3>
<h3>Selected Value: <span class="value"></span></h3>
</div>
控制台日志给出这样的对象:
{
// ...skipped lines
"handleObj": {
"type": "change",
"origType": "change",
"guid": 1,
"selector": "select.mySelector",
"needsContext": false,
"namespace": ""
}
}
【讨论】:
即使在弃用和删除“selector”属性后也可以完全使用任何 jQuery 版本
我的解决方案是在 jQuery 对象初始化时拦截选择器,同时使用继承透明地维护所有其他 jQuery 功能,如下所示:
$ = (function (originalJQuery)
{
return (function ()
{
var newJQuery = originalJQuery.apply(this, arguments);
newJQuery.selector = arguments.length > 0 ? arguments[0] : null;
return newJQuery;
});
})($);
$.fn = $.prototype = jQuery.fn;
用法:
var myAnchors = $('p > a');
var selector = myAnchors.selector;
应该产生:"p > a"
使用 jQuery 3.4.1 成功尝试
【讨论】: