javascript - 如何使用 Js 将 data-bs-target 添加到按钮?

标签 javascript

实际上,我的整个功能都是用 javascript 构建的,我在 Google 上搜索使用 js 添加 data-bs-toggle 但都显示 jquery。 这是我的代码:

function onload_function(params) {
    n = 100
    for (let i = 0; i < n; i++){
        elem = document.getElementById(i)
        //console.log(elem.textContent)
        try{
            console.log(elem.textContent)
            new_elem = document.createElement('button');
            new_elem.innerHTML = elem.textContent;
            new_elem.{{data-bs-target}} = '#support-tab-8'; <-- here
            new_elem.id = 'button-' + i.toString();
            new_elem.classList.add("nav-link");
            document.getElementById("dynamic-headings").appendChild(new_elem);

        }
        catch{
            
        }
    }

最佳答案

您可以使用.dataset 属性访问数据属性,并设置要更改的数据属性的值。 请记住,虽然数据属性是在 html 中以 kebab-case 形式内联编写的,但在 Javascript 中,这些数据属性是通过 camelCase 访问的。 因此,您需要像这样设置值 new_elem.dataset.bsTarget = "YourValue"

我附加了一个演示以下过程的代码片段。

// We want to add the EventListeners only if the DOM is fully loaded to ensure that no issues happen.
document.addEventListener('DOMContentLoaded', function(){

  // Just for the sake of demonstrating I've added a button with an onClick Event to trigger the 
  // change of the Data Attribute. In your code the change within might happen at any point.
  document.getElementById('btnChange').addEventListener('click', function(){
  
    // We need the NodeElement of the Element we want to change the Data Attribute for.
    const el = document.querySelector('.my-span');
    
    // If the Element exists we then change the Data attribute by just accessing the Dataset 
    // property and define a property in the Dataset Object which is called the same as the 
    // Attribute we want to set. But again, keep in mind that we write the Attribute here in 
    // camelCase
    if(el) el.dataset.bsTarget = "MyValue";
  })
});
.my-span[data-bs-target="MyValue"]{
  background-color: red;
}
<div class="container">
  <span class="my-span">My Span Element</span>
  <button id="btnChange">Change Data Attribute</button>
</div>

关于javascript - 如何使用 Js 将 data-bs-target 添加到按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73206767/

相关文章:

javascript - for 循环内 new 运算符时的奇怪行为

javascript - 如何在页面调整大小时重新加载 jQuery 插件?

javascript - 我是否需要关闭每个具有等待结果回调的方法?

javascript - 通过 xmlhttprequest 上传文件生成多部分 : NextPart: EOF

javascript - 显示其选项卡的图标

javascript - Discord.js:如何获取对带有特定表情符号的消息使用react的所有用户,然后将用户列表设置为变量?

javascript - 识别组(数组)中哪个输入触发了事件处理程序

javascript - textmate 重新格式化为 2 个空格

javascript - 如何禁用 slick 插件中的下一步按钮?

javascript - 调用 Javascript 函数并返回响应