psuh data to data attribute



我想使用jQuery将数据推送到元素的data属性。这可能吗?

元素看起来像这样:

<span id="el" data-id="[1]"></span>

和我想得到

<span id="el" data-id="[1, 2]"></span>

如何实现?我知道我可以用$('#el')设置数据值。Data ('id', [1,2,3,4]);但是当我从PHP文件中获取id时(因此我不知道我将获得的id),所以我想我必须使用类似于push()的东西。

您可以使用JSON.parse()然后添加数据并将其转换回字符串以将其设置为数据属性

const el = document.getElementById('el');
const pushElementToData = (elm, prop, data) => {
const prevValue = JSON.parse(elm.dataset[prop]);
const newValue = prevValue.concat(data);
elm.dataset[prop] = JSON.stringify(newValue);
} 
pushElementToData(el, 'id', 2);
console.log(el.outerHTML)
<span id="el" data-id="[1]"></span>

我不确定。这是一个好方法吗?但是它会更新属性值

当一个新的id到达时,你调用updateAttribute函数。

const element = document.getElementById('el');
const updateAttribute = (_element, attr, val) => {
updatedVal = JSON.parse(_element.getAttribute("data-id")).concat(val);
_element.setAttribute("data-id", JSON.stringify(updatedVal)) ;
console.log(_element)
} 
updateAttribute(el, 'data-id', 2);
<span id="el" data-id="[1]"></span>

最新更新