【问题标题】:jQuery attribute name as a dynamic variablejQuery 属性名称作为动态变量
【发布时间】:2020-10-15 23:51:53
【问题描述】:

我正试图将类转换为数据属性,因为我被困在一个只能将类添加到按钮元素的框架中。

jQuery("[class*='data_']").each(function (index) {
  
            var classNames = this.className.split(/\s+/);
            for (var i = 0; i < classNames.length; ++i) {
                if (classNames[i].substr(0, 5) === "data_") {
                   ctargets = classNames[i].slice(5);
                   var target = "data-" + ctargets.split('-')[0];
                   var target_length = (target.length -4);
                   var value = ctargets.slice(target_length);
                  jQuery(this).attr({target:value});
                }
            }
        });

但这实际上是在我的元素中添加了target="value" 而不是data-variable="value"

【问题讨论】:

  • 能否请您展示一些类名的示例以及value 的来源?
  • 该类的属性名称和value 是什么?
  • 目标 = target 值 = home-macinesdata-target="home-machines"

标签: jquery attr


【解决方案1】:

您可以通过更少的字符串操作(以及更少的 jQuery)来实现这一点

const t1 = performance.now()

// A regex test for data_attr-
const rx = /^data_\w+-/

document.querySelectorAll("[class*='data_']").forEach(el => {
  Array.from(el.classList).filter(c => rx.test(c)).forEach(c => {
    const [ dataAttr, value ] = c.split(/-(.+)/)
    el.setAttribute(dataAttr.replace("_", "-"), value)
  })
})

const t2 = performance.now()

document.getElementById("out").textContent = document.getElementById("in").innerHTML

console.log(`Operation took ${t2 - t1}ms`)
pre { white-space: pre-line; }
<div id="in">
<a class="mirror data_target-home-machines" href="#">Home Machines</a>
</div>
<pre id="out"></pre>

特别感谢 this answer 的精彩 String.prototype.split() 技巧

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多