繁体   English   中英

Onclick javascript 函数仅在第二次单击时起作用

[英]Onclick javascript function working only on second click

 function toggleDivFunction() { var arrowElement = document.getElementById("arrowRight"); var showElement = document.getElementById("dropdownText"); arrowElement.onclick = function() { if (showElement.style.display == 'none') { showElement.style.display = 'block'; document.getElementById("arrowRight").style = "transform: rotate(+90deg)"; } else { showElement.style.display = 'none'; document.getElementById("arrowRight").style = "transform: rotate(0deg)"; } } }
 <p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p> <div class="dropdownText" id="dropdownText"><p>TEXT TO BE SHOWN</p></div>

问题是dropdownText div 仅在第二次单击arrowRight跨度后才会显示。 我已将其视为常见问题,但仍然未能找到解决方案。 任何帮助,将不胜感激。

您不需要在另一个click事件处理程序中bind一个click事件处理程序。 您必须使用click事件处理程序。

show/hide功能属于第二个click事件处理程序,并且在第一次clickbinded到您的span DOM 元素。

 function toggleDivFunction () { var arrowElement = document.getElementById ("arrowRight"); var showElement = document.getElementById ("dropdownText"); if(showElement.style.display == 'none') { showElement.style.display = 'block'; document.getElementById("arrowRight").style = "transform: rotate(+90deg)"; } else { showElement.style.display = 'none'; document.getElementById("arrowRight").style = "transform: rotate(0deg)"; } }
 <p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p> <div class="dropdownText" id="dropdownText"> <p>TEXT TO BE SHOWN</p></div>

只是添加到批准的答案。

检查showElement.style.display == ''
此外,如果您使用display = 'none'作为默认值,则在第一次单击时切换到 flex。

例子:

..
if (showElement.style.display == 'none' || showElement.style.display == '') {
..

如果文本样式为display = 'none'

您想更早地分配事件处理程序:

window.onload=toggleDivFunction;

并删除onclick='toggleDivFunction()' ,它当时是不必要的并且是老式的。

您的代码在触发事件时分配一个侦听器(toggleDivFunction)。 要触发侦听器 (arrowElement.onclick),您需要引发另一个事件进行第二次 click

删除arrowElement.onclick = function() {}

为什么?

您已经在onclick=toggleDivFunction()带有arrowRight的函数。 arrowRight首先执行toggleDivFunction()然后执行Dom arrowElement.onclick使用任何一个 onclick 函数,而不是两者

 function toggleDivFunction() { var arrowElement = document.getElementById("arrowRight"); var showElement = document.getElementById("dropdownText"); if (showElement.style.display == 'none') { showElement.style.display = 'block'; document.getElementById("arrowRight").style = "transform: rotate(+90deg)"; } else { showElement.style.display = 'none'; document.getElementById("arrowRight").style = "transform: rotate(0deg)"; } }
 <p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p> <div class="dropdownText" id="dropdownText"> <p>TEXT TO BE SHOWN</p> </div>

暂无
暂无

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

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