JS中点击按钮后Label无法添加到页面的问题
问题解决:Label标签无法显示的原因及修复方案
问题出在document.createElement第二个参数的属性名写法上——DOM属性名需要用驼峰格式,而不是HTML属性的小写形式:
- HTML里的
for属性,在JS DOM中对应的是htmlFor(因为for是JavaScript的关键字,不能直接用) - 文本内容对应的DOM属性是
textContent,不是小写的textcontent
你的代码里这两个属性名写错了,导致Label没有内容也没关联到输入框,所以看起来像是没被添加(实际上它被添加了,但为空,肉眼看不到)。
修正后的代码
方式一:直接在createElement中用正确的DOM属性名
function testFunction2(){ const testinput = document.createElement("input",{type:"text",id:"test"}) const testlabel = document.createElement("label",{htmlFor:"test",textContent:"Test"}) document.body.appendChild(testlabel); document.body.appendChild(testinput); }
方式二:创建元素后单独赋值属性(更直观,不易出错)
function testFunction2(){ const testinput = document.createElement("input"); testinput.type = "text"; testinput.id = "test"; const testlabel = document.createElement("label"); testlabel.htmlFor = "test"; testlabel.textContent = "Test"; document.body.appendChild(testlabel); document.body.appendChild(testinput); }
两种方式都能正常显示Label和输入框,第二种方式因为分开赋值,属性名更清晰,不容易出现大小写或命名错误。
内容的提问来源于stack exchange,提问作者GarnetPilfer
相关产品推荐
相关产品推荐

