使用jQuery添加动态数据属性

时间:2022-11-27 11:34:08

Is there a way to add a "dynamic" data-attribute to a DOM element with jQuery?

有没有办法使用jQuery向DOM元素添加“动态”数据属性?

This, for example, doesn't work:

例如,这不起作用:

var value = 100;

// hoping to add a 'data-100' attribute 
$('div').attr({
  String('data-' + value) :'display: block'
});

It throws the error:

它抛出错误:

Uncaught SyntaxError: Unexpected token (

obs: as far as I know if you sum a string with an integer in JS, it will cast everthing as a String, but anyway I tried with String() because maybe in some language that worked for me once.

obs:据我所知,如果你在JS中用一个整数对一个字符串求和,它会把它作为一个字符串进行转换,但无论如何我尝试使用String(),因为可能用某种语言对我有效。

This obviously won't work (it will add the 'custom_data' and not the 'data-100' attribute):

这显然不起作用(它将添加'custom_data'而不是'data-100'属性):

var custom_data = 'data-100';

// hoping to add a 'data-100' attribute 
$('div').attr({
  custom_data :'display: block'
});

1 个解决方案

#1


2  

Do

$('div').attr("data-"+value,"display:block");

Your syntax is wrong see similar

你的语法错了,看得类似

Fiddle

#1


2  

Do

$('div').attr("data-"+value,"display:block");

Your syntax is wrong see similar

你的语法错了,看得类似

Fiddle