使用 jQuery .attr 或 .prop 设置属性值不起作用 [英] Using jQuery .attr or .prop to set attribute value not working

查看:114
本文介绍了使用 jQuery .attr 或 .prop 设置属性值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个按钮,其属性名为loaded",初始值为no".单击按钮后,我正在运行一些 ajax,在它的最后,我试图将已加载"属性设置为是",这样如果用户多次单击按钮,ajax 就不会再次运行.

I've created a button with an 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 run again if the user clicks on the button more than once.

我有这样的东西:http://jsfiddle.net/PDW35/2/

单击按钮不会将加载更改为是".但是,如果您在 .attr 调用后立即发出警报,如下所示:

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.

如果我使用 .prop() 而不是 .attr() ,它的行为方式都是一样的.我是否在这里遗漏了一点,或者 .prop().attr() 只是不适用于自定义属性?

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?

根据以下评论使用 ajax 更新了 jsfiddle:http://jsfiddle.net/PDW35/5/

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

推荐答案

我不完全确定原始代码不起作用的原因,但 $this 似乎是原因因为某些原因.试试下面的,它似乎工作.Fiddle 来了.

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

参考这个 thread 这似乎是 $this 在 AJAX 调用中似乎不起作用.

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

这篇关于使用 jQuery .attr 或 .prop 设置属性值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆