[英]jQuery click if else only fires once and not when clicked
I am trying to create a mobile menu that has a burger menu, and when you click that menu, it should slide up and down. 我正在尝试创建一个带有汉堡菜单的移动菜单,当您单击该菜单时,它应该上下滑动。 Before I implement this, I am testing how the jQuery code would work and I can only get it to console log when the page loads and not when you click the actual button.
在我实现之前,我正在测试jQuery代码的工作方式,我只能在页面加载时将其设置为控制台日志,而不是在单击实际按钮时。
jQuery: jQuery的:
function mobileMenu() {
$('.mobile-menu-button').click(function() {
$(this).data('clicked', true)
});
if ($('.mobile-menu-button').data('clicked')) {
console.log("Clicked!")
} else {
console.log("Not Clicked!")
}
};
mobileMenu();
For some reason it only console logs 'Not Clicked!' 出于某种原因,它只控制日志'未点击!' when you load up the page.
当你加载页面时。 But it isn't responsive when you actually click the button.
但实际点击按钮时它没有响应。
Into your function you add handler for a button. 在您的函数中,您可以为按钮添加处理程序。 It set data-clicked to true only when you click on it.
只有在单击时才将数据单击设置为true。
Checking for data('clicked') executed immediately. 检查数据('clicked')立即执行。 If you set this param like into next code
如果你将这个param设置为下一个代码
<button class="mobile-menu-button" data-clicked="true">Click me</button>
you will receive into console "Clicked!". 你会收到控制台“Clicked!”。 In the next case
在下一个案例中
<button class="mobile-menu-button">Click me</button>
you will receive "Not Clicked!" 你会收到“没有点击!”
You are only performing the console.log once, when the mobileMenu() function is called. 当调用mobileMenu()函数时,您只执行一次console.log。 Simply updating the data inside the event handler will not cause the function to fire again, you need to explicitly put the function call inside your event handler, either by moving the event handler outside of the function, or having it call a different function, like so:
简单地更新事件处理程序内部的数据不会导致函数再次触发,您需要通过在函数外部移动事件处理程序或让它调用不同的函数来显式地将函数调用放入事件处理程序中,例如所以:
function logger() { if ($('.mobile-menu-button').data('clicked')) { console.log("Clicked!") } else { console.log("Not Clicked!") } } function mobileMenu() { $('.mobile-menu-button').click(function() { $(this).data('clicked', true) logger(); }); logger(); }; mobileMenu();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="mobile-menu-button">Button</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.