简体   繁体   English

用户在父div中单击时单击按钮

[英]click button when user clicks in parent div

I have this code for some elements in my web that I want to do this: 我有我的网络中的一些元素的代码,我想这样做:

When user clicks in a div, trigger a click on the button inside div (in this case, these buttons open a modal), This works in other places in the page where I make a window.location instead a trigger. 当用户点击div时,触发div内部按钮的单击(在这种情况下,这些按钮打开一个模态),这在我创建window.location而不是触发器的页面的其他位置。 What is bad with this code? 这段代码有什么不好的地方? I dont know it :( 我不知道:(

Sorry my english, thanks. 对不起我的英文,谢谢。

jQuery(".hover-content").click(function(e){
        var hl = jQuery(this);
        jQuery(this).find("button").each(function(){
            if(jQuery(this).is(":visible")){
                jQuery(this).trigger("click");
            }
        });
    });

Console shows this error: 控制台显示此错误:

Uncaught RangeError: Maximum call stack size exceeded 未捕获RangeError:超出最大调用堆栈大小

Little example: https://jsfiddle.net/z0704nss/ 小例子: https//jsfiddle.net/z0704nss/

It's because of event bubbling in Javascript. 这是因为Javascript中的事件冒泡
I'm able to replicate and resolve it by using adding e.stopPropagation() to your piece of code. 我可以通过在你的代码片段中添加e.stopPropagation()来复制和解决它。

 $(".hover-content").click(function(e){ e.preventDefault(); console.log('hi') e.stopPropagation(); $(this).find("button").each(function(){ if($(this).is(":visible")){ $(this).trigger("click"); } }); }); $('.button-ex').click(function(e){ e.preventDefault(); e.stopPropagation(); console.log('clicked button') }) 
 body { background-color: #eef; padding: 5px; } .hover-content{ background-color:#FF0000 } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="hover-content"> <button id="btnOne" class="button-ex">demo1</button> <button id="btnTwo" class="button-ex">demo2</button> </div> 

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

相关问题 当用户单击按钮时显示表单并将其添加到div - Display and add a form to a div when a user clicks a button 用户单击按钮时显示div元素的错误 - Bug displaying a div element when a user clicks on a button 当用户单击浏览器的后退按钮时隐藏div - Hide div when user clicks browser's back button 用户单击指向新页面的按钮时的单击事件 - On click event when user clicks a button that leads to a new page 当用户单击按钮时,向下滚动到特定的div - Scroll down to specific div when the user clicks the button 当用户单击浏览器操作按钮时,是否有任何方法可以检测到Shift-click或Control-click? - Is there any way to detect a shift-click or control-click when a user clicks the browser action button? 如何在用户单击其子元素时阻止父点击事件? AngularJS - How to prevent parent click event when the user clicks on his child element? AngularJS 当用户单击以关闭浏览器时,JavaScript确认触发(但单击刷新按钮时,则不触发) - JavaScript confirm to fire when user clicks to close their browser (but not when they click the refresh button) 显示一个 <div> 当用户单击带有href“#”的链接时 - Show a <div> when the user clicks a link with href “#” 当用户点击它时更改 div 的颜色 - Change the color of div when user clicks over it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM