我试图在我的<p>
中调用一个函数,该函数应该调用数字(while循环)1到25。但是我不确定如何前进。
如何在不使用console.log()
或document.write()
而不是使用document.createElement
和node.append
的情况下将此信息附加到段落标记中?
如何在DOM HTML的p标签内调用此函数?
function oneThroughTwentyFive() {
let count = 1
while(count <= 25) {
count++
}
}
答案 0 :(得分:1)
这将呈现一个<p>
元素,其中包含数字1到25。
<html>
<body>
</body>
<script>
let p = document.createElement('p');
let script = document.createElement('script');
script.innerHTML = `
let numbers = "";
for (let e = 1; e <= 25; e++) numbers += e + " ";
document.currentScript.parentNode.innerHTML = numbers;
`
p.appendChild(script)
document.body.appendChild(p)
</script>
</html>
这基本上是做什么的:
<p>
元素<script>
元素<script>
中
元素<script>
元素追加到<p>
元素<p>
元素(现在其中包含Javascript代码)
身体这是<p>
元素中的JavaScript的作用:
<p>
其中包含<script>
<p>
元素的全部内容(包括用于创建数字的JS代码)。用于创建数字的Javascript代码不见了,所以最后一个元素看起来像这样:
<p>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25</p>
答案 1 :(得分:0)
那个?
const pTag = document.querySelector('p#pTag')
for (let i=1;i<=25;++i) pTag.textContent += i+' '
// -------------------------------------------
// the method name say's all
let otherP = document.createElement('p')
// just a trick as many in JS
otherP.textContent = Array.from(Array(10),(_,i)=>i+25).join(' ')
// append otherP in the right place on the DOM
document.body.appendChild( otherP )
<p id="pTag"></p>