Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - How can I set data-* attributes on the button when the AJAX requests complete?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...