jQuery -参数解析器"为类

jQuery - "argument parser" for classes

本文关键字:quot 为类 参数 jQuery      更新时间:2023-09-26

我试图通过应用于这些插件所附加的元素的类来配置jQuery插件。

例如:

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

和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
});

它适用于这种特殊情况,但由于我也在为其他插件这样做,我想知道如何为这种通过类传递的选项创建某种"解析器",因此我可以编写更少的代码:)

您的示例使用jQuery进行重构。data和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
});

另一个很好的选择是jquery元数据插件:

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