开发者

Why is this expression always false?

I'm creating a Q&A site that allows users to vote on answers. I've set project.problem.upVoted to a list of answers which the user has already upvoted. If the answer is already voted on, the callback for the upvote arrow's click event should delete the current vote, and if it's not already voted on, it should vote for it.

Here's the callback function for my upa开发者_JAVA百科rrow image:

project.problem.upVoteCallback = function(event)
{
    var answerID = $(this).parents("div.answer").find("input.answerID").attr("value");
    var isUpVoted = $.inArray(answerID, project.problem.upVoted) > -1;

    //some debug statements
    alert("id: " + answerID + " | upvoted: " + project.problem.upVoted);
    alert("isupvoted: " + isUpVoted);

    if(isUpVoted)
    {
        //delete vote
    }
    else
    {
        //cast upvote
    }
}

The problem is that isUpVoted is always false. For example, on my test page, when I try deleting a vote I get this output:

id: 91 | upvoted: 91,92,93 
isupvoted : false

Yet if I copy the predicate to chrome's js console while substituting answerID with 91 it evaluates to true:

$.inArray(91, project.problem.upVoted) > -1; 
true


When you put the value of the input into answerID, its type is a string, not an integer. You need to cast the variable to an integer, like such:

var isUpVoted = $.inArray(parseInt(answerID), project.problem.upVoted) > -1;

This will make sure that jQuery's inArray function compares the same data types, instead of comparing a string to integers.


Make sure the value that you are checking is an int:

var isUpVoted = $.inArray(parseInt(answerID), project.problem.upVoted) > -1;

Also you might want to make sure that the values in the array are also of the int type.


Try:

var answerID = $(this).parents("div.answer").find("input.answerID").val();
var isUpVoted = $.inArray(+answerID, project.problem.upVoted) > -1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜