繁体   English   中英

为什么我必须点击两次才能让这个 JavaScript function 起作用?

[英]Why do I have to click twice for this JavaScript function to work?

为了将显示更改为“隐藏”然后返回“阻止”的功能,每次都需要点击 2 次。 为什么是这样? 如何将其减少到只需单击一下?

 function showOfferMessage() { var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); } }
 <div class="offer-row collapsible" id="'.$oid.'" onclick="showOfferMessage()"> <div class="offer-info-item"> <div class="offcatreview-title"> <h3>Cat. Rating</h3> </div> <div class="offer-cat-rating"> </div> </div> </div> <div class="content"> <p>'.$message.'</p> </div>

那是因为您在每次点击时都注册了一个事件侦听器! 因此,每次单击时,您的侦听器都会再次执行一次。

您的代码已修复:

 function showOfferMessage(element) { element.classList.toggle("active"); var content = element.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }
 <div class="offer-row collapsible" id="'.$oid.'" onclick="showOfferMessage(this)"> <div class="offer-info-item"> <div class="offcatreview-title"> <h3>Cat. Rating</h3> </div> <div class="offer-cat-rating"> </div> </div> </div> <div class="content" style="display: block"> <p>'.$message.'</p> </div>

onclick事件执行showOfferMessage() {}函数,该函数将事件侦听器放在"collapsible"元素上。 然后第二次点击执行事件监听器的内容。

但首先,只要您只有一个名为"collapsible"元素,为什么要尝试获取多个元素。 执行document.querySelector并使用 css 样式选择器定位元素,然后将addEventListener直接链接到该选择器上。

当您像这样查询样式时,您会得到显式设置的样式。 在您的情况下,如果没有点击"collapsible"元素,则不会设置显示样式。 即使 div 具有块的默认显示样式,它也没有被明确设置,所以...style.display将返回一个空字符串 -> falsy。 您必须使用getComputedStyle方法获取隐式样式,

像这样( codepen ):

document.querySelector(".collapsible").addEventListener("click", function() {
  console.log(this);
  this.classList.toggle("active");
  var content = document.querySelector(".content");
  console.log(window.getComputedStyle(content).display);
  if (window.getComputedStyle(content).display === "block") {
    content.style.display = "none";
  } else {
    content.style.display = "block";
  }
});

我可能会在事件侦听器中使用箭头函数

document.querySelector(".collapsible").addEventListener("click", event => {
  console.log(event.target);
  event.target.classList.toggle("active");
  var content = document.querySelector(".content");
  console.log(window.getComputedStyle(content).display);
  if (window.getComputedStyle(content).display === "block") {
    content.style.display = "none";
  } else {
    content.style.display = "block";
  }
});

我有类似的问题,最终使用 !== 而不是 ===

if (content.style.display !== "none") {
    content.style.display = "none";
  } else {
    content.style.display = "block";
  };

暂无
暂无

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

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