0

我想用变量更改属性名称。但是,我无法理解如何仅访问常量。在以下示例中,我想更改所有以“monkey”开头的属性名称并将它们更改为“banana”,但保持破折号和数字不变。

更改以下内容:

<div monkey-20="delicious" monkey-100="delicious">

对此:

<div banana-20="delicious" banana-100="delicious">

有人有提示吗?

4

1 回答 1

1

我可以争辩说,您更改属性名称的具体要求有些不寻常,因此 jQuery 插件形式的有点非正统的解决方案可能对您有用:

$.fn.renameAttrs = function() {
  var oldName = arguments[0] + '-',
      newName = arguments[1] + '-';

  return this.each(function() {
    var $node = $(this),
        attrs = [];

    $.each(this.attributes, function() {
      var index = this.name.indexOf(oldName);

      if (!index) {
        $node.attr(newName + this.name.substr(oldName.length), this.value);
        attrs.push(this);
      }
    });

    $.each(attrs, function() {
      $node.removeAttr(this.name);
    });
  });
};
于 2014-04-09T02:24:05.133 回答