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);
I would suggest you make
targetSelectora function, wherethisrefers to the current.triggerand 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
targetSelectoraccept both, a selector string and a function, and then handle the value accordingly.Example: