在 jQuery 中获取插件绑定的元素?

Getting the element that the plugin was binded to in jQuery?

我一直在制作我的第一个 jQuery 插件,我需要通过样式标签在 head 中添加一些 CSS,就像在被脚本注入的元素在 IE8 - 10 中有一些奇怪的错误。

但是要在头部添加样式,我需要将用户绑定插件的实际元素作为目标。

例如:

$('input').myPlugin(); // I need to get the text "input"
$('#form .foo').myPlugin(); // I need to get the text "#form .foo"

是否可以在插件中获取这些数据?

该字符串是对象的选择器属性:

$.fn.myPlugin = function(){
    console.log(this.selector);
}
$('#form .foo').myPlugin(); // logs '#form .foo'

但使用它看起来是一种不好的做法(而且它也被弃用,正如 charlietfl 所指出的,有充分的理由)。你不应该需要它。给元素设置样式你可以直接做

$.fn.myPlugin = function(){
    this.css('color', 'red');
}

$.myPlugin

解决您的问题的推荐方法是使用 this 和下面描述的其他方法。如果您需要选择器作为字符串,您可以将函数定义为 jQuery ($) 的子函数,并以与 jQuery 的 &.[ 类似的方式执行函数。 =33=] 和 $.extend。它正在做的是使它成为 jQuery 的子项和 $.fn 的子项,因此它仍然可以 'classified' 作为常规 jQuery 插件或原型jQuery。当你旧设置你的插件 $.fn 时,它被设置为 jQuery 的原型,所以你必须 运行 jQuery 功能。我们在这里这样做,但因为函数也是对象,我们可以将该函数设置为 $.myPlugin 使其仍然是 jQuery 的一部分,但会阻止用户输入选择器两次。由于 this.selector 已弃用 (它可能很快就会被删除) 它比 运行 通过函数生成选择器更好。

$.myPlugin = $.fn.myPlugin = function (selector) {
    console.log(selector);
}

$.myPlugin('#selector'); //Logs: '#selector

The $.fn is completely optional and is there just in case a user forgets to execute the function using $.myPlugin(selector) the function will still work when using $().myPlugin(selector)

其他选择

如果您不需要字符串,我建议您使用 jQuery 的 .filter() or similar functions (here) 以及 $(this).

$.fn.myPlugin = function () {
    var $this = this;
    var filteredElements = $this.children('a');//

    console.log(filteredElements);
} 
$('#form .class').myPlugin();
//Logs: children that are <a> of #form .class

尝试

$.fn.myPlugin = function(sel) {
  console.log(sel, $(this));
};
var selectors = ["input", "#form .foo"];
$(selectors[0]).myPlugin(selectors[0]); // I need to get the text "input"
$(selectors[1]).myPlugin(selectors[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<input type="text" />
<form id="form">
  <select class="foo" name="foo">
    <option value="abc">abc</option>
  </select>
</form>