将数据属性添加到元素并从类名

时间:2016-05-12 06:40:00

标签: jquery

我想为一个元素添加一个data-attribute,并动态地为它赋予与类名相同的值。

我已经使用这个脚本从元素的字符串中做同样的事情 - 但我想从类名中传递值,而不知道如何做到这一点。

脚本:

$('.newgroup').attr('data-price', function() {
var text = $(this).text();
return parseInt(text, 10); 
});

HTML

<div class="newgroup">/div>

应该是这样的:

<div class="newgroup" data-price="newgroup">>/div>

2 个答案:

答案 0 :(得分:2)

只需写下以下内容:

$(".newgroup").attr("data-price", $('.newgroup').attr('class'));

.attr 设置属性值, .attr('class')返回 classname

请参阅plunkr

正如您在屏幕截图中看到的,添加了属性

enter image description here

答案 1 :(得分:2)

您可以使用以下内容将// note, for readability I changed the explicit types to keyword var to make the code a little more compact and hopefully easier identify the changes var apps = await PContext.Appointments.Select(p => p).Where(p => p.Start >= Start && p.End <= End && p.MachineId == 66).ToListAsync(); // Retrieve all instances on the context in one call foreach (var app in apps) { await PContext.Entry(app).ReloadAsync(); // execute each Reload synchronously instead of concurrently } 分配为类名

attribute

请参阅demo