javascript - 根据元素的 ID 设置元素的数据属性

标签 javascript jquery html css-selectors getelementbyid

我正在尝试设置此元素的 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.setAttributeHTMLElement.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/

相关文章:

javascript - 带有 javascript 文件的 html 图表

javascript - Jquery 滚动到顶部偏移量不起作用

php - 使用 PHP 将 MYSQL 查询中的元素添加到 HTML 表

html - margin float 的替代品 : auto issues

javascript - 无法通过 java 脚本更新 grid-template-areas css 属性

javascript - Eslint 解析错误 : Unexpected token

javascript - 如何使用 JavaScript 将元素添加到列布局

javascript - 将表列 append 到 td 标签内带有 span 标签的表

jquery - 如何通过 HTML 和 JQUERY 中的选项正确禁用和启用输入字段

html - 有什么方法可以使用 wkhtmltopdf 减小文件大小?