简体   繁体   English

通过单击另一个按钮来委派一个按钮单击事件

[英]Delegating a button click event by clicking another button

我想通过单击另一个按钮来触发HTML按钮单击事件,有人可以帮助我提供代码,我正在使用jQuery库。

You mean something like this? 你的意思是这样的吗?

$('#button1').click(function() {
    $('#button2').click();
});

If click is called without passing an argument, it will trigger the click event on that element. 如果在没有传递参数的情况下调用click ,它将触发该元素上的click事件。

Documentation is helpful . 文档很有帮助

Update regarding your comment: 有关您的评论的更新:

Have you had this problem? 你有这个问题吗? My small tests show that the code is executed in order, meaning, code after triggering the click is executed after the click handler. 我的小测试表明,代码是按顺序执行的,也就是说,触发点击后的代码是在点击处理程序之后执行的。 But maybe my handler is not complex enough... 但是也许我的处理程序不够复杂...

If you indeed experience problems, you could put all the code that is executed in the #button2 click handler in its own function and call this one in the #button1 click handler: 如果你确实遇到问题,你可以把所有在执行的代码#button2单击处理程序在其自身的功能,并呼吁这一个在#button1单击处理程序:

function lotsOfWork() {

}

$('#button2').click(lotsOfWork);

$('#button1').click(function() {
    lotsOfWork();
    // more stuff here
});

If lotsOfWork is doing some asynchronous calls you also have to make the function accept a callback that will be executed after it finishes its work. 如果lotsOfWork正在执行一些异步调用,则还必须使该函数接受一个在其完成工作后将执行的回调。

try something like this: 尝试这样的事情:

<input type="button" id="btn1" value="click A">
<input type="button" id="btn2" value="click B">
<script>
$(function(){
    $('#btn1').click(function(){
        $('#btn2').trigger('click');
    })
})
</script>

to fire events of other objects you just have to call the .trigger method, passing the event name that you pretend to fire. 要触发其他对象的事件,您只需调用.trigger方法,并传递您假装要触发的事件名称。

$('#buttonone').click(function(){
  $('#buttontwo').trigger('click')
})

Clicking on buttonone will trigger a click on buttontwo 点击buttonone会触发点击button2

$(function(){
    $("#id_btn").click(function(){
                call your function for 2nd button
    });
});
or
$('#id_btn').bind('click', function() {
    $('#id_btn').trigger('click');
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM