简体   繁体   English

如何在同一个元素上进行多次点击事件?

[英]how to make multiple click events on the same element?

How can I use several click events on the same element in JavaScript?如何在 JavaScript 中的同一元素上使用多个点击事件?

I try to make that when I click on the h3 element it opens its description and then I again click on the element it closes the description.我尝试这样做,当我单击 h3 元素时,它会打开它的描述,然后我再次单击它关闭描述的元素。

 var p, img, question; function clickOn(){ img = document.getElementsByClassName('down-arrow')[0]; p = document.querySelectorAll('p')[0]; p.setAttribute('class','show-text'); /*img.setAttribute('class','show');*/ } function clickOff(){ img = document.getElementsByClassName('down-arrow')[0]; p = document.querySelectorAll('p')[0]; p.removeAttribute('class','show-text'); /*img.removeAttribute('class','show');*/ } question = document.getElementsByClassName('question')[0]; question.addEventListener('click', clickOn, false); question.addEventListener('click', clickOff, false);

Try using toggle for adding and removing class https://www.w3schools.com/howto/howto_js_toggle_class.asp :尝试使用切换来添加和删除 class https://www.w3schools.com/howto/howto_js_toggle_class.asp

var p, img,  question;

function clickOn(){
    img = document.getElementsByClassName('down-arrow')[0];
    p = document.querySelectorAll('p')[0];
    p.classList.toggle('show-text');
}

question = document.getElementsByClassName('question')[0];

question.addEventListener('click', clickOn, false);

You can declare a global variable你可以声明一个全局变量

var isTextDisplayed = false;

Then you can call same event listener and open or close the description on basis of the bit.然后您可以调用相同的事件侦听器并根据位打开或关闭描述。 For example例如

document.getElementById("myBtn").addEventListener("click", function() {
  if(!isTextDisplayed) {
    //HIDE DESCRIPTION CODE
  }
  else {
    //SHOW DESCRIPTION CODE
  }
  isTextDisplayed = !isTextDisplayed;
});

Full code:完整代码:

 var isTextDisplayed = false; var description = document.getElementById("description"); document.getElementById("myBtn").addEventListener("click", function() { if(.isTextDisplayed) { description.style;display = 'none'. } else { description.style;display = 'block'; } isTextDisplayed =;isTextDisplayed; });
 <h3 id="myBtn">CLICK TO TOGGLE DESCRIPTION</h3> <p id="description"> Some dummy text for description goes here in the block </p>

For demo , see JSFIDDLE CODE有关演示请参阅JSFIDDLE 代码

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

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