简体   繁体   English

将 function 添加到 DOM 元素中

[英]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.createElementnode.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:基本上这是做什么的:

  1. Create a <p> element创建一个<p>元素
  2. Create a <script> element创建一个<script>元素
  3. Add the Javascript code to display the numbers into the <script> element添加 Javascript 代码以将数字显示到<script>元素中
  4. Append the <script> element to the <p> element Append <script>元素到<p>元素
  5. Append the <p> element (which now has the Javascript code within it) to the body Append <p>元素(现在其中包含 Javascript 代码)到正文

And this is what the Javascript in the <p> element does:这就是<p>元素中的 Javascript 的作用:

  1. Loop through all numbers from 1 to 25遍历从 1 到 25 的所有数字
  2. Add each number plus a space (so the numbers won't be jammed up against each other) to the numbers variable将每个数字加上一个空格(这样数字就不会相互干扰)添加到数字变量中
  3. Find the parent element of the current script (in this case the <p> which contains the <script>查找当前脚本的父元素(在本例中为包含<script><p> >
  4. Overwrite the entire content of the <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM