向DOM元素添加功能

时间:2020-08-20 00:37:33

标签: javascript

我试图在我的<p>中调用一个函数,该函数应该调用数字(while循环)1到25。但是我不确定如何前进。

如何在不使用console.log()document.write()而不是使用document.createElementnode.append的情况下将此信息附加到段落标记中?

如何在DOM HTML的p标签内调用此函数?

function oneThroughTwentyFive() {
  let count = 1
  while(count <= 25) {
    count++
  }
}

2 个答案:

答案 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>

这基本上是做什么的:

  1. 创建一个<p>元素
  2. 创建一个<script>元素
  3. 添加Javascript代码以将数字显示到<script>中 元素
  4. <script>元素追加到<p>元素
  5. 附加<p>元素(现在其中包含Javascript代码) 身体

这是<p>元素中的JavaScript的作用:

  1. 浏览从1到25的所有数字
  2. 添加每个数字加一个空格(这样数字不会被卡住 对立)到数字变量
  3. 找到当前脚本的父元素(在本例中为<p> 其中包含<script>
  4. 用数字覆盖<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>