Using jQuery.attr or .prop to set attribute value does not work

I created a button with an attribute named "loaded" and the initial value is "no." After clicking the button, I start some ajax, and at the very end I try to set the loaded attribute to yes so that ajax does not start again if the user clicks the button more than once.

I have something like this: http://jsfiddle.net/PDW35/2/

Pressing the button does not switch to yes. However, if you run the warning immediately after calling .attr as follows:

alert($(this).attr('loaded')); 

the warning field contains β€œyes”, which does not help, because as soon as the user clicks, the same code displays a β€œno” warning.

Everything behaves the same if I use .prop instead of .attr. Am I missing a point here or is .prop and .attr just not working with custom attributes?

EDIT: Updated jsfiddle using ajax, based on the comments below: http://jsfiddle.net/PDW35/5/

+6
source share
4 answers

I'm not quite sure about the reason why the source code is not working, but the reason for $this for some reason. Try below and it seems to work. Fiddle is here.

I will try to update the answer for a reason as soon as I find it.

 var loaded = $(".preview-button").attr('data-loaded'); if (loaded === "no") { $.ajax({ success: function (result) { $(".preview-button").attr('data-loaded', 'yes'); alert($(".preview-button").attr('data-loaded')); } }); } else { alert("data loaded"); } 

Post this thread , and this seems to be the reason $this not working due to an AJAX call.

+3
source

reading the question ..

so that ajax does not start again if the user clicks the button more than once.

I think you need one() , this allows the event to fire only once .. there is no need to change attributes and properties

Example

  $(".preview-button").one('click',function(){ //your ajax stuff alert('clicked!!!!'); }); 
+1
source

You can set a property for your click (or submit ) function:

 $( ".preview-button" ).click( function() { this.ajaxCompleted = this.ajaxCompleted || false; if ( !this.ajaxCompleted ) { // run your request and set this.ajaxCompleted to true in a callback; } // do other stuff } ); 
0
source

you can try the following code: after you click the data, it will load a second time to warn that the data is already loaded.

 $(".preview-button").click(function(){ var id = $(this).attr('button_id'); var loaded = $(this).attr('loaded'); if(loaded == "no"){ $(this).attr('loaded', 'yes'); }else{ alert("Data is loaded"); } }); 

working example here: http://jsfiddle.net/PDW35/4/

0
source

Source: https://habr.com/ru/post/950793/


All Articles