簡體   English   中英

在 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" ); 但按鈕仍然沒有點擊頁面打開。 我怎樣才能做到這一點? 我不能只調用該函數,因為我收到錯誤“無法讀取未定義的屬性‘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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM