问题
This is a follow up question for the one asked before https://stackoverflow.com/a/33550107/4662074
And to be honest I just need a hint here. I have the jquery validate submit handler and it calls the ajax query. This query returns some data and I want this data to be used when user clicks a button on the webpage.
Now, the user suggests that I cannot use the click hangler attached to the button inside the submit handler of my validate. But how can I pass the data there?
I have my button in html:
<a class="btn btn-default" data-transaction="" name="submitForm" id="submitForm" >Submit</a>
I added there a data-transaction now. And in my submit handler I'm doing:
success: function(response) {
var myNumber= (response[0].myNumber);
$("#submitForm").attr('data-transaction', myNumber);
alert(myNumber);
That alerts me my number. But when I do this outside of the success function:
$("#submitForm").on('click', function() {
var number_id = $("submitForm").attr('data-transaction');
alert("number: "+number_id );
});
}
it prints me: number: undefined. How can I pass this value then?
回答1:
Use jquery data instead:
$("#submitForm").data('transaction', transactionID);
And
var number_id = $("#submitForm").data('transaction');
Notice that this will not add the attribute to the DOM, if you inspect the element via the developers tool, you won't see data-transaction, but the element will have the data referenced.
Edit:
Your method should also work, but as @Tushar pointed out, you are missing the # from your selector: $("submitForm") -> $("#submitForm")
来源:https://stackoverflow.com/questions/33570437/how-can-i-set-data-attributes-on-the-button-when-the-ajax-requests-complete