如果循环中属性值和 ID 值相同,条件将如何工作

How the condition will work if the attribute value and the ID value are the same through the loop

<style>

    .heading {
        color: red;
    }
    
    .button {
        font-size: 18px;
    }
    
    .skyblue {
        background-color: skyblue;
    }
</style>
如果

标签的"data-mh"和

此代码通过遍历每个按钮并完成事件侦听器和比较的所有设置来完成任务。

// select all the buttons
const buttons = document.querySelectorAll(".button");

// loop over each one
for(const button of buttons)
{
  // add an on click listener
    button.addEventListener("click", (event) => {
    // get the button ID
    const x = button.getAttribute("id");
    /// get the previous element's (the heading's) data-mh attribute
    const z = button.previousElementSibling.getAttribute("data-mh");
    // compare them
    if(x == z)
    {
      button.classList.toggle("skyblue");
      document.getElementById("demo").innerHTML = x+" "+z;
    }
  });
}

这是一个演示:https://jsfiddle.net/w3d0z8Ly/

检查我的回答:-

var x = document.querySelectorAll(".heading"); // This variable is to get Attribute of "data-mh"
    var y = document.querySelectorAll(".button"); // Button selection. By clicking this button I will get print my Attribute
    // var z = y.getAttribute("id"); // Getting button id to compaire with "data-mh" attribute
    function btnClick(e) {
      for(var i = 0; i < x.length; i++) {
        if(e.getAttribute("id") == x[i].getAttribute("data-mh"))  {
          document.getElementById("demo").innerHTML = x[i].getAttribute("data-mh");
        }
      }
      for(var j = 0; j < y.length; j++) {
        y[j].classList.remove("skyblue");  
      }
      e.classList.add("skyblue");
    }
      
.heading {
        color: red;
    }
    
    .button {
        font-size: 18px;
    }
    
    .skyblue {
        background-color: skyblue;
    }
<h1 class="heading" data-mh="item1">Hello World</h1><button class="button" id="item1" onClick="btnClick(this)">Click Here</button>

<h1 class="heading" data-mh="item2">Hello World</h1>
<button class="button" id="item2" onClick="btnClick(this)">Click Here</button>

<h1 class="heading" data-mh="item3">Hello World</h1>
<button class="button" id="item3" onClick="btnClick(this)">Click Here</button>

<p id="demo"></p>

请检查这个

const buttons = document.querySelectorAll(".button");
const headings = document.querySelectorAll(".heading");

for (const button of buttons) {
  for (const heading of headings) {
    button.addEventListener("click", (event) => {
      const x = button.getAttribute("id");
      const z = heading.getAttribute("data-mh");
      if (x == z) {
        button.classList.toggle("skyblue");
        document.getElementById("demo").innerHTML = x + " " + z;
      }
    });
  }
}