
[英]How to run click event handler in Internet Explorer 10 using jquery?
[英]Trigger button click event programmatically using JavaScript or jQuery on page load in Internet Explorer
我有这段代码
window.onload = function () {
$('#btnFilter').click(function (e) {
btnFilter(e);
});
}
该功能适用于单击按钮,但我需要在页面打开时单击该按钮。 我试过 $('#btnFilter').trigger( "click" ); 但按钮仍然没有点击页面打开。 我怎样才能做到这一点? 我不能只调用该函数,因为我收到错误“无法读取未定义的属性‘currentTarget’”,因为我没有提供任何事件作为参数。
function btnFilter(e) {
element = e.currentTarget.parentElement;
//other code
}
你可以这样尝试:
$(document).ready(function(){
$('#btnFilter').trigger('click');
});
$(document).on('click','#btnFilter',function(e){
btnFilter(e);
});
function btnFilter(e)
{
element = e.currentTarget.parentElement;
}
您可以更改“btnFilter”以接受按钮而不是事件:
function btnFilter(element) {
element = element.parentElement;
...
}
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this); return false; });
// Pass the button to the filter operation on load
btnFilter($("#btnFilter")[0]);
});
或者,直接接受父元素
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this.parentElement); return false; });
// Pass the button parent to the filter operation on load
btnFilter($("#btnFilter")[0].parentElement);
});
如果你使用 jquery,我会保持它的连贯性,而不是将它与 vanilla javascript 混合使用。 Jquery 解决方案是:
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(function(){$("#btnFilter").click()});
要么
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(btnFilter);
在您的解决方案中,错误是事件绑定:当您在页面加载时将事件绑定到#btnFilter
时,该元素尚不存在,因此无法触发该功能。
jQuery 解决方案:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").trigger("click");
});
</script>
</head>
<body>
<button onclick="alert('clicked')">Click</button>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.