简体   繁体   English

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

[英]not able to change the color of text on button click

on clicking the button the paragraphs are not getting colored, I'm not able to get the reason behind this.单击按钮时,段落没有着色,我无法理解其背后的原因。

<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";
  }
}

why this works without adding semicolons in query selector(document.querySelectorAll("#" + id + " p"));.为什么在查询选择器(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";
  }
}

There is an issue in your querySelector Here is the right code您的querySelector存在问题 这是正确的代码

var paragraphs = document.querySelectorAll(`${id} p`);

Here is the working code.这是工作代码。

 <;DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <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> <script> console;clear(). 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"; } } </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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