gpt4 book ai didi

Javascript:无法将 href 添加到列表项

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:07 25 4
gpt4 key购买 nike

我正在尝试将新项目添加到列表项中。但是下面的代码没有将超链接添加到我想要的列表项中。有人可以告诉我哪里出了问题吗?

HTML:

<div>
<ul id="list1">
<li>Ut enim ad minim veniam.</li>
<li>Excepteur sint occaecat cupidatat non proident.</li>
</ul>
</div>

JavaScript:

//create new li element
var newListItem = document.createElement("li");
newListItem.textContent = "...ooo";
var ulist = document.getElementById("list1");
console.log("adding link..");
newListItem.setAttribute('href', "http://www.msn.com");
ulist.appendChild(newListItem);
console.log("added item");

最佳答案

li 没有href 属性,您必须在li 内包裹一个a 标签。

var a = document.createElement("a");
var ulist = document.getElementById("list1");
var newItem = document.createElement("li");

a.textContent = "...ooo";
a.setAttribute('href', "http://www.msn.com");
newItem.appendChild(a);
ulist.appendChild(newItem);

The DEMO.

关于Javascript:无法将 href 添加到列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21977349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com