在 Internet Explorer 中加载页面时使用 JavaScript 或 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" );但按钮仍然没有点击页面打开。我怎样才能做到这一点?我不能只调用该函数,因为我收到错误 "Cannot read property 'currentTarget' of undefined" 因为我没有提供任何事件作为参数。

function btnFilter(e) {
    element = e.currentTarget.parentElement;
    //other code
}

您可以更改 '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,我会保持它的连贯性,而不是将它与原版 javascript 混合。 Jquery 解决方案是:

$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(function(){$("#btnFilter").click()});

$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(btnFilter);

在您的解决方案中,错误是事件绑定:当您在页面加载时将事件绑定到 #btnFilter 时,该元素尚不存在,因此无法触发该功能。

你可以这样试试:

$(document).ready(function(){
    $('#btnFilter').trigger('click');
});

$(document).on('click','#btnFilter',function(e){
    btnFilter(e);
});

function btnFilter(e)
{
    element = e.currentTarget.parentElement;
}

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>