JQuery problems with setting variables in if/else
I'm trying to set a variable to 0 if an item attribute is equal a specific string, else set the variable to 1, but I can't get it to work.
My code is like this in my javascript 开发者_JAVA百科function:
var variable;
if ($(this).attr("attribute", "string"))
variable=0;
else
variable=1;
For some reason, the variable always get set to 0, even if the item attribute isn't equal the specific string.
What am I doing wrong??
You have to use this instead:
var variable;
if ($(this).attr("attribute") == "string")
variable=0;
else
variable=1;
$(this).attr("attribute", "string")
sets the attribute attribute
to string
, it doesn't test if attribute
equals string
.
See the attr(attributeName,value)
method documentation.
Try -
var variable;
if ($(this).attr("attribute") == "string")
variable=0;
else
variable=1;
This compares the value of attribute "attribute"
to the value "string"
. What you're doing at the moment is setting the value of attribute "attribute"
to the value "string"
. I suspect this function will return a "truthy" value hence variable
always being set to 0.
You are setting the string in your if
if( $(this).attr("attribute", "string") ){
You need to read it and compatre
if( $(this).attr("attribute") === "string") ){
Try $(this[attribute="string"])
.
精彩评论