为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

长风秋雁 2022-09-02 21:39:14
点击按钮,段落没有变色,我无法理解这背后的原因。<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";  }}
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

您的代码中存在问题,这是正确的代码querySelector


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

下面是工作代码。


<!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>


查看完整回答
反对 回复 2022-09-02
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信