[英]Adding a function into a DOM element
I am trying to call an function into my <p>
which should call the numbers(while loop) 1 to 25. But I'm not sure how to move forward.我正在尝试将 function 调用到我的
<p>
中,它应该调用数字(while 循环)1 到 25。但我不确定如何前进。
How would I append this info into the paragraph tag without using console.log()
or document.write()
but using instead document.createElement
and node.append
to insert my results into HTML?我如何在不使用
console.log()
或document.write()
而是使用document.createElement
和node.append
将我的结果插入 HTML 的情况下将此信息 append 插入段落标记?
How would I call this function inside ap tag in a DOM HTML?我如何在 DOM HTML 的 ap 标签内调用这个 function?
function oneThroughTwentyFive() {
let count = 1
while(count <= 25) {
count++
}
}
This will render a <p>
element with the numbers 1 through 25 within it.这将呈现一个
<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>
Basically what this does is:基本上这是做什么的:
<p>
element<p>
元素<script>
element<script>
元素<script>
element<script>
元素中<script>
element to the <p>
element <script>
元素到<p>
元素<p>
element (which now has the Javascript code within it) to the body <p>
元素(现在其中包含 Javascript 代码)到正文And this is what the Javascript in the <p>
element does:这就是
<p>
元素中的 Javascript 的作用:
<p>
which contains the <script>
<script>
的<p>
><p>
element (including the JS code used to create the numbers) with the numbers.<p>
元素的全部内容(包括用于创建数字的 JS 代码)。 The Javascript code used to create the numbers is gone, so the final element will look like this:用于创建数字的 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>
that?那?
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.