![](/img/trans.png)
[英]how to dynamically add REQUIRED attribute to input tags based on output of select tag using 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應該看看...
對象. 分配,
HTMLElement
的dataset
屬性
並從選擇器 API 進入例如querySelector
。
下面提供的示例代碼使用的基於Object.assign
的方法將第二個提供的源元素的dataset
對象... document.querySelector('#mycode')
... 合並到第一個提供的目標元素的dataset
對象中... document.body
。 這意味着前者的每個屬性都作為屬性分配給后者,因此也會覆蓋同名的已經存在的屬性。
筆記
?.
是Optional Chaining Operator ,它允許以失敗保存方式訪問鏈式屬性(如果屬性不存在)。
??
是Nullish Coalescing 運算符,它在這里用於在左側值是null
或undefined
的情況下回退到默認值。
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.