开发者

jQuery: apply plugin dynamically

开发者 https://www.devze.com 2022-12-13 03:36 出处:网络
i\'m having this markup: <div plug=tButton></div> and wrote a little plugin which makes a button ouf of the div like this:

i'm having this markup:

<div plug=tButton></div>

and wrote a little plugin which makes a button ouf of the div like this:

var cmd = $("[plug]");
cmd.tButton();

my question: when only having the div (and its plug-attribute), how ca开发者_JAVA技巧n i apply the corresponding plugin to it (without using eval)?

it should be like:

var plug = div.attr("plug");
div[plug];

but doesn't work obviously.

thx.


I'd consider using classes, to distinguish which elements get which plugins and apply them using selectors. Assuming that the classes have the same name as the plugin, you can index into the jQuery object, too, to apply it.

$(function() {
   $('.tButton').tButton();
   $('.jButton').jButton();
   ...
});

or

$(function() {
   var plugins = [ 'tButton', 'jButton', ... ];
   $.each(plugins, function(i,val) {
       $('.' + val).each( function() {
          jQuery[val].apply(this);
       });
   });
});

<div class="tButton">...</div>
<div class="jButton">...</div>


I don't quite understand what you're trying to do, but my best guess is this:

  • You're setting these divs with custom attributes, and using jQuery to
    • Style them as buttons
    • Add interactive behavior to them

I've already tried to offer a solution based on your question, but if I understand what you're doing correctly, it seems like a simpler approach would be this:

  • Give your elements different classes instead of custom attributes like plug=
  • Use CSS to take care of styling them like buttons. Consider using an actual button element instead of a div
  • Use jQuery and your custom plugin (if you like) to add any behaviors you want

Does that make sense, or am I missing something?


Given your markup, if you're trying to apply your tButton() plugin, I think you'd just do this:

$("div[plug='tButton']").tButton();
$("div[plug='xButton']").xButton();


I think you want this

$('div[plug]').each(function() {

    var $this = $(this);
    var plugin = $this.attr('plug');
    $this[plugin]();

});

but this is probably not the best way to do things in terms of performance. I would suggest using a CSS class to identify the elements that you want to apply your plugin to, then call the plugin function on the collection returned using the appropriate class selector. For example, if the elements are always <div> elements

$('div.tButton').tButton();


You almost have it. You just need to call the function you looked up. Do this:

var plug = div.attr("plug");
div[plug]();
0

精彩评论

暂无评论...
验证码 换一张
取 消