jQuery属性名称作为动态变量
我正在尝试将类转换为数据属性,因为我被困在一个框架中,在这个框架中,a只能向按钮元素添加类jQuery属性名称作为动态变量,jquery,attr,Jquery,Attr,我正在尝试将类转换为数据属性,因为我被困在一个框架中,在这个框架中,a只能向按钮元素添加类 jQuery("[class*='data_']").each(function (index) { var classNames = this.className.split(/\s+/); for (var i = 0; i < classNames.length; ++i) { if (c
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});
}
}
});
jQuery(“[class*='data\']”)。每个(函数(索引){
var classNames=this.className.split(/\s+/);
对于(变量i=0;i
但这实际上是在我的元素中添加了
target=“value”
,而不是data variable=“value”
,您可以通过更少的字符串操作(以及更少的jQuery)实现这一点
const t1=performance.now()
//数据属性的正则表达式测试-
常数rx=/^data\uw+-/
document.querySelectorAll(“[class*='data']”)。forEach(el=>{
数组.from(el.classList).filter(c=>rx.test(c)).forEach(c=>{
常量[dataAttr,value]=c.split(/-(.+)/)
el.setAttribute(dataAttr.replace(“\”,“-”,值)
})
})
const t2=性能。现在()
document.getElementById(“out”).textContent=document.getElementById(“in”).innerHTML
log(`Operation take${t2-t1}ms`)
pre{空白:pre-line;}
您可以通过更少的字符串操作(以及更少的jQuery)实现这一点
const t1=performance.now()
//数据属性的正则表达式测试-
常数rx=/^data\uw+-/
document.querySelectorAll(“[class*='data']”)。forEach(el=>{
数组.from(el.classList).filter(c=>rx.test(c)).forEach(c=>{
常量[dataAttr,value]=c.split(/-(.+)/)
el.setAttribute(dataAttr.replace(“\”,“-”,值)
})
})
const t2=性能。现在()
document.getElementById(“out”).textContent=document.getElementById(“in”).innerHTML
log(`Operation take${t2-t1}ms`)
pre{空白:pre-line;}
你能展示一些类名和value
应该来自哪里的示例吗?以及该类的属性名和value
是什么吗?target=target
value=home macines
iedata target=“home machines”
你能展示一些类名的例子和value
应该来自哪里吗?以及该类的属性名和value
是什么吗?target=target
value=home macines
iedata target=“home machines”