[英]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.