无法更改按钮单击上的文本颜色

点击按钮,段落没有变色,我无法理解这背后的原因。


<button onclick="changeBackGroundOfPs('#firstDiv');">Change backgrounds of p under a given element known by id</button>

  <br>

<div id="firstDiv">

  <p>First paragraph.</p>

  <p>Second paragraph.</p>

</div>

function changeBackGroundOfPs(id ) {

  var paragraphs = document.querySelectorAll(id   p);


  // Another way to iterate on all elements in a collection

 for (var i = 0; i < paragraphs.length; i++ ) {

   paragraphs[i].style.backgroundColor = "lightGreen";

  }

}

为什么这可以在查询选择器(document.querySelectorAll(“#” + id + “ p”)中添加分号的情况下工作);.


<button onclick="changeBackGroundOfPs('firstDiv');">Change backgrounds of p under a given element known by id</button>

  <br>

<div id="firstDiv">

  <p>First paragraph.</p>

  <p>Second paragraph.</p>

</div>

function changeBackGroundOfPs(id) {

  var paragraphs = document.querySelectorAll("#" + id + " p");


  // Another way to iterate on all elements in a collection

  for (var i = 0; i < paragraphs.length; i++ ) {

    paragraphs[i].style.backgroundColor = "lightGreen";

  }

}


长风秋雁
浏览 76回答 1
1回答

白板的微信

您的代码中存在问题,这是正确的代码querySelectorvar paragraphs = document.querySelectorAll(`${id} p`);下面是工作代码。<!DOCTYPE html><html><head>&nbsp; <meta charset="utf-8">&nbsp; <meta name="viewport" content="width=device-width">&nbsp; <title>JS Bin</title></head><body><button onclick="changeBackGroundOfPs('#firstDiv');">Change backgrounds of p under a given element known by id</button>&nbsp; <br><div id="firstDiv">&nbsp; <p>First paragraph.</p>&nbsp; <p>Second paragraph.</p></div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <script>&nbsp; &nbsp; console.clear();&nbsp; &nbsp; function changeBackGroundOfPs(id ) {&nbsp; &nbsp; &nbsp; var paragraphs = document.querySelectorAll(`${id} p`);&nbsp; &nbsp; &nbsp; // Another way to iterate on all elements in a collection&nbsp; &nbsp; &nbsp; for (var i = 0; i < paragraphs.length; i++ ) {&nbsp; &nbsp; &nbsp; &nbsp; paragraphs[i].style.backgroundColor = "lightGreen";&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript