[英]Javascript function document.createElement(tagName[, options]) doesn't work as intended
我需要在一個 js 代碼行中創建<a href="http://someurl.com"></a>
元素
這不起作用:
var gg = document.createElement("a", {href : "http://someurl.com"})
這導致: <a is="[object Object]"></a>
思想 MDN 說: var element = document.createElement(tagName[, options]);
options 是一個可選的 ElementCreationOptions 對象。 如果此對象已定義並具有is
屬性, is
所創建元素的is
屬性將使用此屬性的值進行初始化。 如果對象沒有is
屬性,則值為 null。 https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
這個 ElementCreationOptions 對象是某種奇異的對象嗎? 我圍繞這個對象嘗試了許多不同的組合,但沒有任何效果,結果總是我看到奇怪的is
屬性! 我還在規范中找到了它: https : //www.w3.org/TR/custom-elements/#attr-is但不知道它實際上是如何工作的。
ps:這也不起作用:
var gg = document.createElement("a").setAttribute("href" , "someurl.com")
導致未定義。
我知道這是一個古老的問題(相對而言),@Luke-Weaver 的回答已經給出了一條涉及 jQuery 的路線,但以下是一個選項,既可以完成 @Garegin 最初的要求,同時仍然為他提供他想要的功能在使用 vanilla JS 時,createElement 方法的參數名稱不明確。
gg = Object.assign(document.createElement('a'),{href:'http://someurl.com',innerText:"Bonus points?"});
此解決方案在一行中創建'<a href="http://someurl.com">Bonus points?</a>'
。 它更長,所以以下可能效果更好:
function oneLineTag(tag,options){
return Object.assign(document.createElement(tag),options);
}
let quickAnchor = {
href:'http://someurl.com',
innerText: "I'm still answering a 3-year-old question"
}
你現在可以選擇
gg = oneLineTag('a',quickAnchor);
看起來Juhana是正確的,我剛開始不了解規范,因此無法通過options
參數添加任意元素屬性。 謝謝所有回答!
您不能使用第二個 ( ElementCreationOptions ) 參數來添加 html 屬性。
var element = document.createElement(tagName[, options]);
文檔中明確提到第二個可選參數是一個包含單個屬性的對象,即 is。 正如我們在下面看到的,
一個可選的 ElementCreationOptions 對象包含一個名為 is 的屬性,其值為之前使用 customElements.define() 定義的自定義元素的標記名稱。 為了與先前版本的自定義元素規范向后兼容,某些瀏覽器將允許您在此處傳遞字符串而不是對象,其中字符串的值是自定義元素的標簽名稱。 有關如何使用此參數的更多信息,請參閱擴展本機 HTML 元素。
來到你的問題,解決方案如下,
var body = document.body || document.getElementsByTagName('body')[0];
var anchor = document.createElement('a');
anchor.href = 'http://someurl.com';
var text = document.createTextNode("http://someurl.com");
anchor.appendChild(text);
body.appendChild(anchor);
讓我知道它是否有效。
我相信 create element 函數的第二個參數僅適用於自定義元素。 相反,您可以使用 jQuery 的 .attr 來創建/設置屬性,如下所示:
var gg = $(document.createElement("div")).attr("href", "someurl.com");
如果您不使用 jquery,您可能會不走運(至少如果您試圖將其全部放在一行中)。 我會說使用 .setAttribute() 但是我注意到你不能將它鏈接到對象構造函數的末尾並且還沒有找到解決這個問題的方法。
試試這個方法。
var gg = document.createElement("div")
document.body.appendChild(gg);
var att = document.createAttribute( "href" );
att.value = "someurl.com" ;
gg.setAttributeNode(att);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.