在jquery中为单击添加回调

ajr*_*ton 2 javascript jquery

我有一个按钮(比如按钮A),它将点击事件转发到另一个按钮(比如按钮B).

$("#buttonA").click(function()
{
  $("buttonB").click();
});
Run Code Online (Sandbox Code Playgroud)

但是现在我希望它在按钮B事件完成后从按钮A触发时在回调函数中执行其他操作.问题是,我希望使用的语法与将click事件绑定到按钮B相反:

$("#buttonA").click(function()
{
  $("#buttonB").click(function()
  {
    alert("I want this to happen only after buttonA is clicked and buttonB's onclick event finishes.")
  });
});
Run Code Online (Sandbox Code Playgroud)

我理解为什么上面的内容不起作用,但我应该在这里做些什么呢?

注意:ButtonB正在进行异步ajax表单提交.

Kar*_*non 5

这样做时:

$("#buttonA").click(function()
{
  $("#buttonB").click(function()
  {
    alert("I want this to happen only after buttonA is clicked and buttonB's onclick event finishes.")
  });
});
Run Code Online (Sandbox Code Playgroud)

你绑定了一个事件#buttonB,这不是你想要的.只需在代码之后插入代码.click(),它将在click事件完成后执行:

$("#buttonA").click(function()
{
  $("#buttonB").click();
  alert("I want this to happen only after buttonA is clicked and buttonB's onclick event finishes.");
});
Run Code Online (Sandbox Code Playgroud)

按钮b是异步的

b是异步的,你不应该使用匿名函数.trigger().在这里你可以做什么:

function doSomething(e){
    e = typeof e === "undefined" ? new Event() : e;
    //your code when b is clicked...

    //Then ajax
    return $.ajax('www.example.com');
}

$('#buttonB').on('click', doSomething);

$('#buttonA').on('click', function(){
    doSomething().done(function(){
        alert("I want this to happen only after buttonA is clicked and buttonB's onclick event finishes.")
    })
})
Run Code Online (Sandbox Code Playgroud)