简体   繁体   中英

How to trigger another jquery event using the return data of previously executed jquery event

I have a button, for example

<a id="btn" class="button">Submit</a>

When this button is clicked, it triggers a jquery function

for example,

$("#btn").on("click", function() {
  $.ajax({
    url: 'index.php',
    type: 'post',
    data: {product_id: 1, qty: 2},
    dataType: 'json',
    success: function(json) {
       if (json['success']) {
          console.log('Product added to cart');
       }
       if (json['error']) {
          console.log('Product not added to cart');
       }
    });
});

Now, I would like to know if it is possible to trigger another jquery event by some other jquery code, once the above function is executed, and I want to use the return values of the previous function without making any changes to the above-mentioned function.

For example, I would like to run the following function immediately after the above jquery event by writing another jquery code and not changing any part of the previous code.

function anotherAction(json_array) {
    if (json_array['success']){
        //calling another function
    }
}

You mean

function anotherAction() {
  if (submitBtn() == 'Submitted'){
    console.log('Button is submitted');
  }
}

But then you need to make str global in scope

Perhaps like this

 let str; $("#btn").on("click", function() { str = 'Submitted'; }); $("#check").on("click", anotherAction); function anotherAction() { console.log('Button has '+(str === 'Submitted'? "": "not ")+'been clicked'); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="btn" type="button">Click</button> <button id="check" type="button">Check</button>

without making any changes to the above-mentioned function.

No. Its not possible. submitBtn function's return value is unused/no-reference/destroyed inside "#btn" click event. So you'll never know what was returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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