开发者

jQuery - "argument parser" for classes

开发者 https://www.devze.com 2023-02-28 15:48 出处:网络
I\'m trying to configure jQuery plugins trough classes applied to elements to which these plugins are attached.

I'm trying to configure jQuery plugins trough classes applied to elements to which these plugins are attached.

for example:

<div class="move amt-10 dir-left">
...
</div>

and the js:

$('.move').each(function(){
  var classes 开发者_高级运维= $(this).attr('class');

  // this is from: http://stackoverflow.com/questions/3955345/javascript-jquery-get-number-from-string
  var amount = parseInt(/amt-(\d+)/.exec(classes)[1], 10);
  var direction = /dir-([^\s]+)/.exec(classes)[1];
  // do stuff here based on amount/direction variables
});

it works for this particular case, but since I'm doing this for other plugins too, I was wondering how could create some kind of "parser" for this kind of options passed trough classes, so I can write less code :)


Your example refactored using jQuery.data and HTML5 data-* attributes

<div class="move" data-amt="10" data-dir="left"></div>

$('.move').each(function(){
  var amount = $(this).data('amt');
  var direction = $(this).data('dir');
  // do stuff here based on amount/direction variables
});


Another good option for this sort of thing is the jquery metadata plugin:

http://plugins.jquery.com/project/metadata

0

精彩评论

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

关注公众号