Using jQuery .attr or .prop to set attribute value

2020-07-10 08:45发布

I've created a button with attribute named 'loaded' and initial value of 'no'. Upon clicking the button I'm running some ajax and at the very end of it I'm trying to set the 'loaded' attribute to 'yes' so that the ajax is not ran again if the user clicks on the button more than once.

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

Clicking the button does not change loaded to 'yes'. However, if you do an alert right after the .attr call like this:

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

the alert box does contain 'yes' which doesn't help because once the user clicks, the same code above puts up a 'no' alert box on the screen.

It all behaves the same way if I use .prop instead of .attr. Am I missing a point here or .prop and .attr just don't work with custom attributes?

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

4条回答
虎瘦雄心在
2楼-- · 2020-07-10 09:25

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.

查看更多
一夜七次
3楼-- · 2020-07-10 09:39

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/

查看更多
祖国的老花朵
4楼-- · 2020-07-10 09:49

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
} );
查看更多
孤傲高冷的网名
5楼-- · 2020-07-10 09:50

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!!!!');
 });
查看更多
登录 后发表回答