Using jQuery .attr or .prop to set attribute value not working

℡╲_俬逩灬. 提交于 2019-12-04 07:11:58
Harry

I am not exactly sure of the reason why the original code isn't working, but the $this seems to be the cause for some reason. Try the below and it seems to work. Fiddle is here.

I will try to update the answer with the 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");
}

Refer this thread and this seems to be the reason why the $this doesnt seem to work from inside the AJAX call.

reading the question ..

so that the ajax is not ran again if the user clicks on the button more than once.

i think you need one(), it allows the event to run just once.. no need of changing the attributes and properties

example

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

You can set 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
} );

you could try the following code: once you clicked data is loaded, second time click will alert that data is loaded already.

$(".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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!