我有这段代码
window.onload = function () {
$('#btnFilter').click(function (e) {
btnFilter(e);
});
}
该功能在单击按钮时起作用,但是我需要在页面打开时单击按钮。我已经尝试过$('#btnFilter')。trigger(“ click”);但按钮仍未在打开页面时单击。我怎样才能做到这一点?我不能只调用该函数,因为我没有给出任何事件作为参数,因此收到错误消息“无法读取未定义的属性'currentTarget'”。
function btnFilter(e) {
element = e.currentTarget.parentElement;
//other code
}
答案 0 :(得分:1)
您可以更改“ 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);
});
答案 1 :(得分:1)
如果您使用jquery,我会使其保持连贯性,而不是将其与普通javascript混合使用。一个Jquery解决方案是:
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(function(){$("#btnFilter").click()});
或
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(btnFilter);
在您的解决方案中,错误是事件绑定:在页面加载时将事件绑定到#btnFilter
时,该元素尚不存在,因此无法触发该函数。
答案 2 :(得分:1)
您可以尝试这样:
$(document).ready(function(){
$('#btnFilter').trigger('click');
});
$(document).on('click','#btnFilter',function(e){
btnFilter(e);
});
function btnFilter(e)
{
element = e.currentTarget.parentElement;
}
答案 3 :(得分:0)
jQuery解决方案:
paddingEnd