我需要在一行 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属性,则值为空。
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")
导致未定义。
Sam*_*hes 18
我知道这是一个古老的问题(相对而言),@Luke-Weaver 的回答已经给出了一条涉及 jQuery 的路线,但以下是一个选项,既可以完成 @Garegin 最初的要求,同时仍然为他提供他想要的功能在使用 vanilla JS 时,createElement 方法的参数名称不明确。
gg = Object.assign(document.createElement('a'),{href:'http://someurl.com',innerText:"Bonus points?"});
Run Code Online (Sandbox Code Playgroud)
此解决方案'<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"
}
Run Code Online (Sandbox Code Playgroud)
你现在可以选择
gg = oneLineTag('a',quickAnchor);
Run Code Online (Sandbox Code Playgroud)
Tai*_*iti -1
试试这个方法。
var gg = document.createElement("div")
document.body.appendChild(gg);
var att = document.createAttribute( "href" );
att.value = "someurl.com" ;
gg.setAttributeNode(att);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19569 次 |
| 最近记录: |