繁体   English   中英

如果语句无法在ajax内成功运行

[英]If statement not working inside ajax success

我有这个HTML代码

<div class="vote">
    <div data-post-id="@item.PostId" data-vote-rank="1" class="vote-arrow vote-up glyphicon glyphicon-chevron-up"></div>
    <div class="total-vote">0</div>
    <div data-post-id="@item.PostId" data-vote-rank="-1" class="vote-arrow vote-down glyphicon glyphicon-chevron-down"></div>
</div>

而这个jQuery ajax帖子

$(".vote-arrow").click(function () {
    var postId = $(this).data("post-id");
    var voteRank = $(this).data("vote-rank");

    $.ajax({
        type: "GET",
        url: "/Posts/Vote/",
        data: { postId: postId, voteRank: voteRank },
        context: this,
        success: function () {
            console.log(voteRank); //working, I get 1
            if (voteRank === "1") {
                console.log(voteRank); //nothing in the console
                $(this).css({ 'color': 'red' });
            }
            alert("working");
        }
    });
});

success if陈述不起作用。

如果按data-vote-rank="1"按div,则从console.log在if语句之外的控制台中获得1,在if语句之后得到alert 如果调试,if-statement条件中的voteRank为1,但是我没有在if-statement中获得console.log(当然也不会改变颜色)。

怎么了?

使用==voteRank === 1 ,身份( === )运算符还检查类型,它们必须匹配才能被视为相等。

.data()内部将值转换为适当的数据类型。 它们不是字符串。 1 === "1"将评估为false

在这种情况下,jQuery会将data属性转换为数字。 .data()文档中

会尝试将字符串转换为JavaScript值(包括布尔值,数字,对象,数组和null)。 仅在不更改值表示形式的情况下,将值转换为数字。 例如,“ 1E02”和“ 100.000”等价于数字(数值100),但对其进行转换将改变其表示形式,因此它们保留为字符串。 字符串值“ 100”将转换为数字100。

您应该更改if语句的条件以反映此情况:

 if (voteRank === 1) {
    // snip
 }

您是否尝试过将结果转换为int。 您可以在将值应用于“ if”条件之前使用parseInt()。

$(".vote-arrow").click(function () {
    var postId = $(this).data("post-id");
    var voteRank = $(this).data("vote-rank");
    $.ajax({
        type: "GET",
        url: "/Posts/Vote/",
        data: { postId: postId, voteRank: voteRank },
        context: this,
        success: function () {
            console.log(voteRank); //working, I get 1
            if (parseInt(voteRank) === 1) {
                console.log(voteRank); //nothing in the console
                $(this).css({ 'color': 'red' });
            }
            alert("working");
        }
    });
});

身份(===)运算符的行为与相等(==)运算符相同,只是不进行类型转换,并且类型必须相同才能被视为相等。

因此,在使用它之前,请将左侧变量类型转换为与右侧变量类型相同。 在Ur解决方案中将voteRank转换为int

voteRank = parseInt(voteRank, 10);

然后检查

if (voteRank) === 1) {

            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM