jQuery 属性名作为动态变量
jQuery attribute name as a dynamic variable
我正在尝试将 类 转换为数据属性,因为我被困在一个只能将 类 添加到按钮元素的框架中。
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"
您可以通过更少的字符串操作(以及更少的 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()
技巧
我正在尝试将 类 转换为数据属性,因为我被困在一个只能将 类 添加到按钮元素的框架中。
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"
您可以通过更少的字符串操作(以及更少的 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()
技巧