如何将 jQuery 选择器链传递给我的插件?
我对 jQuery 很陌生,我需要解决选择问题。我有许多带有 class="trigger"
的触发器,在这些触发器上调用 jQuery 插件函数 myFunc
。
触发器可以是图像或链接,每个触发器必须引用带有class="target"
的输入字段(文本框或文本区域)。
这是一个示例,但请注意,targets
可能先于或后,最终触发
中的某些元素>之间:
<a class="trigger">trigger 1</a>
<input class="target" type="text" /><!-- target for trigger 1 -->
<a class="trigger">trigger 2</a>
<textarea class="target"></textarea><!-- target for trigger 2 -->
问题是我需要传递targetSelector
(例如.next('.target')
或其他东西取决于 DOM)到我的插件,以便获得每个触发器的每个目标元素:
$('.trigger').myFunc({ // Plugin invokation
targetSelector : <code here> // Pass something like .next('.target')
});
(function($) { // Plugin defininition
$.fn.myFunc = function(options) {
this.each(function() { // Iterate each trigger
var target = <code here>; // Get target for current trigger
};
};
})(jQuery);
I'm quite new to jQuery and i need to solve a selection problem. I have many triggers with class="trigger"
on which jQuery plugin function myFunc
is invoked.
Triggers can be images or links and each trigger must refer to an input field (textbox or textarea) with class="target"
.
Here is an example, but please note that targets
may precede or follow triggers
eventually with some elements in between:
<a class="trigger">trigger 1</a>
<input class="target" type="text" /><!-- target for trigger 1 -->
<a class="trigger">trigger 2</a>
<textarea class="target"></textarea><!-- target for trigger 2 -->
The problem is i need to pass a targetSelector
(like .next('.target')
or somthing else depending on DOM) to my plugin, in order to get each target element for each trigger:
$('.trigger').myFunc({ // Plugin invokation
targetSelector : <code here> // Pass something like .next('.target')
});
(function($) { // Plugin defininition
$.fn.myFunc = function(options) {
this.each(function() { // Iterate each trigger
var target = <code here>; // Get target for current trigger
};
};
})(jQuery);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您将
targetSelector
设为一个函数,其中this
引用当前的.trigger
并返回相应的目标:
.call()
[docs]:这为您提供了最大的灵活性,您可以在此函数中执行您想要的任何 DOM 遍历。
当然,您可以使其更加复杂,让
targetSelector
接受选择器字符串和函数,然后相应地处理该值。例子:
I would suggest you make
targetSelector
a function, wherethis
refers to the current.trigger
and it returns the corresponding target:Which can be implemented with
.call()
[docs]:This gives you the greatest flexibility and you can perform any DOM traversal you want in this function.
Of course you can make it more sophisticated and make
targetSelector
accept both, a selector string and a function, and then handle the value accordingly.Example:
使用自定义属性而不是依赖 .next 或 .prev,因为您必须检查 prev 和 next 才能查看现在哪个属性正在检索。
例子
use a custom attribute instead of relying on .next or .prev as you would have to check prev and next to see which one retrives the right now.
Example