簡體   English   中英

如何在 Javascript 中使用 html 屬性創建元素標簽

[英]How to createElement tag with html attributes in Javascript

我在我的 html 源代碼的某個元素之后插入了一個輸入標簽,它似乎可以工作,但我需要的是能夠向我創建的輸入標簽添加屬性(類型、class、id 等)。

這是我在 Js 中所做的

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var inputCheckBox = document.createElement("input");
inputCheckBox.innerHTML = "test";
var div = document.getElementById("plugin_delete_me_shortcode_password");
insertAfter(div, inputCheckBox);

結果 html

<input type="password" autocomplete="off" autofocus="autofocus" id="plugin_delete_me_shortcode_password" name="plugin_delete_me_shortcode_password">

<input>test</input> <!-- i got this as a new item -->

現在我有兩個問題,1)一般輸入標簽似乎沒有結束標簽,但它們是一行。 2)我不知道如何通過 Js 向標簽添加屬性。

這就是我想要實現的目標,有人可以告訴我正確的方法嗎? 我搜索了一些參考資料,但未能找到解決方案。 我感謝任何幫助,謝謝。

<input type="password" autocomplete="off" autofocus="autofocus" id="plugin_delete_me_shortcode_password" name="plugin_delete_me_shortcode_password">

<input type="checkbox" class="my_class" id="my_id" onclick="my_function('example_function')"/>

您可以在創建元素后將 a 值分配給屬性,如下所示:

 var inputCheckBox = document.createElement("input"); inputCheckBox.type = 'checkbox'; inputCheckBox.id = 'the-id'; inputCheckBox.classList.add('the-class'); // for styling inputCheckBox.style.color = 'green'; // or you can use the set attribute method inputCheckBox.setAttribute('type', 'checkbox'); console.log(inputCheckBox);

嘗試在 inputCheckBox 上調用setAttribute ,例如`

inputCheckBox.type = 'password';    
inputCheckBox.setAttribute('autocomplete', 'off');
...
inputCheckBox.name = "plugin_delete_me_shortcode_password";

您可以將 DOM 用於 Vanilla JavaScript

const element = createElement("div");
div.setAttribute("data-custom-attribute", "custom-value");

如果要使用 JQuery:

$('<div></div>').attr({
  id: "my-id"
})

更多關於這個的官方文檔

暫無
暫無

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

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