我正在尝试设置此元素的 data-whatever
属性:
<a
class='btn-lg btn-success bg-primary'
id='vsIDButton'
data-toggle='modal'
href='#messageModal'
role='button'
data-whatever=''>New Message</a>
现在我设法通过替换整个元素来做到这一点,但应该有更好的方法。
我已经使用innerHTML
尝试过这个以及围绕这个的一些变体:
const vSourceID="contact:7573981724739861";
document.getElementById("vsIDButton.attr('data-whatever')").innerHTML = vSourceID;
我也尝试过在 StackOverflow 中找到的这个 jQuery 函数:
我已经尝试过这两种方法:
SetButton(vSourceID);
function SetButton() {
$('#vsIDButton > data-whatever').html();
}
还有这个:
SetButton(vSourceID);
function SetButton(x) {
$('#vsIDButton > data-whatever').html(x);
}
最佳答案
当您使用 document.getElementById
时,您应该只向其传递 id
属性,在您的情况下为 vsIDButton
。
然后,要设置数据属性,您可以使用 Element.setAttribute
或HTMLElement.dataset
,具体取决于您需要支持的浏览器:
const vSourceID = 'contact:7573981724739861';
// Using setAttribute:
document.getElementById('vsIDButton').setAttribute('data-whatever', vSourceID);
// Using dataset (you only need one or another):
document.getElementById('vsIDButton').dataset.whatever = vSourceID;
#vsIDButton::before {
/*
This will display the value of the data-whatever attribute
in a ::before pseudo-element so that we can easily see that
the JS code is working.
*/
content: attr(data-whatever);
}
<div id="vsIDButton"></div>
请注意,使用dataset
时,不需要添加data-
前缀,因此只需:
document.getElementById('vsIDButton').dataset.whatever = vSourceID;
这些与 Element.innerHTML
无关,用于获取或设置元素中包含的 HTML 或 XML 标记,而不是其属性。
关于javascript - 根据元素的 ID 设置元素的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51349157/