I currently take baby steps in JS development and coded the following link adder:
const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')
button.addEventListener('click', function(){
let input = document.getElementById('text').value
let createA = document.createElement('a')
createA.setAttribute('href', input)
let linkDescr = document.createTextNode(input)
createA.appendChild(linkDescr)
listdiv.appendChild(createA)
})
The order of instruction is this:
Get the value of the text box
Create <a>
Set <a>
's link description
Set href
add <a>
's description to <a>
And then add all of <a>
to the pre-existing Div
..
So far so good. But, why is it that when we set href
, it gets automatically added to <a>
, but we have to take an extra step to add the link's description? Isn't let linkDescr = document.createTextNode(input)
supposed to add the description automatically as well? My theory is that the commands are different in that we directly set an attribute of <a>
for one, but create a variable on the other; and something need's to be done first with this variable. Variables don't just do anything by themselves. Please educate me on my logic. Also feel free to propose code changes/suggestions/flaws.
Thank you
答案 0 :(得分:1)
通常有多种方法可以做。
例如,href
可以像这样添加:
createA.href = input;
然后,描述也可以作为属性添加。
createA.textContent = input;
API简单地给了我们选择。在某些情况下,附加文本节点可能更有意义,例如当您重新定位现有节点时。
在您的情况下,您正在创建一个新的文本节点。这是一个独立于DOM树的任何其他部分的对象,因此在您将其插入所需位置之前它不会执行任何操作,例如在新的a
元素内部。