我创建了一个在 HTMLdiv元素中创建内部元素的脚本。
它工作正常,但我认为我使用字符串的方式在 JavaScript 中不是最合适的。
HTML
<body>
<div class="chart-container">
<div class="chartlyrics">...</div><div class="chartlyrics box" id="powered_by"></div>
</div>
</body>
“ ... ”所在的位置是我创建元素的位置。
Javascript
document.getElementsByClassName('chartlyrics')[0].innerHTML = '<img src="img/103-logo.jpg" class="" /><br />Powered by '
HTML 结果:
<body>
<div class="chart-container">
<div class="chartlyrics"><img src="img/103-logo.jpg" class="" /><br />Powered by </div><div class="chartlyrics box" id="powered_by"></div>
</div>
</body>
在 JavaScript 中创建元素时如何不使用字符串来执行此操作?
我试过了,但它给了我一个语法错误:
document.getElementsByClassName('chartlyrics')[0].innerHTML = ''
var img = document.getElementsByClassName('chartlyrics')
.appendChild(document.createElement("img"));
img.src = "img/103-logo.jpg"
img.class = ""
img.textContent = 'Powered by '
console.log(document.getElementsByClassName('chartlyrics')[0].innerHTML);
结果:
document.getElementsByClassName (...). appendChild is not a function
慕桂英546537
相关分类