当调用自定义插件时,如何获取当前选择器字符串?获取当前的jQuery选择器字符串?
$('my_selector p').my_plugin();
想在我的脚本中输出my_selector p
。我怎样才能访问这个字符串?
当调用自定义插件时,如何获取当前选择器字符串?获取当前的jQuery选择器字符串?
$('my_selector p').my_plugin();
想在我的脚本中输出my_selector p
。我怎样才能访问这个字符串?
jQuery.fn.getSelector = function() {
return this.data('selector');
};
+1显示如何扩展jQuery。使用像这样$('someSelector')。getSelector(); – mindandmedia 2012-02-21 17:24:23
在我的情况下得到了'undefined'(jQuery v2.2.4)。 – 10basetom 2017-06-14 04:35:27
后选择弃用v 1.7:
如果你只处理ID和班级的选择,你可以使用以下命令:
var selector = (typeof($(this).attr('id')) !== 'undefined' || $(this).attr('id') !== null) ? '#' + $(this).attr('id') : '.' + $(this).attr('class');
有更简洁的方式,但因为由于因为1.7是浏览器之间不一致的去除.selector的,这一直是我去。
如果$(this).attr('class')返回多于一个类,该怎么办?这会使一个无效的选择器,你应该做'。'+ $(this).attr('class')。split(“”).join(“。”)。 – vasilevich 2016-12-04 01:08:15
另外,如果选择器是'.unique-class-123 p强。帮助“,它只会返回'.help' – CodeBrauer 2017-10-27 16:21:46
随着部门不赞成我使用
index = document.getElementById('category').value
select = $("#category option[value=#{index}]")[0].innerHTM
的代码只是两行
,或者如果你是用线
select = $("#category option[value=#{document.getElementById('category').value}]")[0].innerHTML
被弃用真的很便宜,官方的建议是增加选择作为参数的函数调用:https://api.jquery.com/selector/
需要在其插件中使用选择器字符串的插件可能需要它作为方法的参数。例如, “foo” 的插件可以写成
$.fn.foo = function(selector, options) { /* plugin code goes here */ };
和使用插件的人会写
$("div.bar").foo("div.bar", {dog: "bark"});
冗余,是的,但它总是可靠的。
重复http://stackoverflow.com/questions/500246/how-do-i-get-a-jquery-selectors-expression-as-text – jbabey 2012-02-21 17:22:22