簡體   English   中英

如何使用 javascript 或 jquery 在另一個標簽中添加一個標簽屬性?

[英]How to add one tags attribute in another tag using javascript or jquery?

我想知道,是否可以使用 javascript 或 jquery 將一個標簽的數據屬性繞過另一個標簽?

例如,如果我在 body 內的任何地方寫這個標簽<span id="mycode" data-attribute="my-code"></span> , data-attribute 標簽將自動附加到 body 標簽<body data-attribute="my-code"></body>

當我創建模板時, <body>標簽沒有任何屬性。 我想要的是,當我用屬性 ( <span data-attribute="my-code"> ) 編寫這個標簽時,只有屬性會被添加到 body 標簽(<body>)中。

如果有人知道,請幫助我。

OP應該看看...

下面提供的示例代碼使用的基於Object.assign的方法將第二個提供的源元素的dataset對象... document.querySelector('#mycode') ... 合並到第一個提供的目標元素的dataset對象中... document.body 這意味着前者的每個屬性都作為屬性分配給后者,因此也會覆蓋同名的已經存在的屬性。

筆記

 console.log('before...', { body: document.body }); Object.assign( document.body.dataset, document.querySelector('#mycode')?.dataset?? {} ); console.log('after...', { body: document.body });
 <span id="mycode" data-attribute="code-one" data-message="Well Done Dear" data-number="5" data-status="Active" >span with a lot of global <code>data-*</code> attributes</span>

您可以使用數據dataset屬性訪問data-XXX屬性。 然后簡單地從一個元素分配給另一個元素。

document.body.dataset.attribute = document.getElementById("mycode").dataset.attribute;

暫無
暫無

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

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