簡體   English   中英

如何使用 Js 將 data-bs-target 添加到按鈕?

[英]How do I add data-bs-target to button using Js?

實際上,我的整個 function 是在 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 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM