javascript 比较两个字符串(jquery .text() 和文字字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18888754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare two strings (jquery .text() and literal string)
提问by user1081577
I'm trying to figure out why this is not working. I'm sure the text is the same. They both return a string. But the if statement is always true even when it's clearly false!... Does anyone know what i'm doing wrong?
我想弄清楚为什么这不起作用。我确定文字是一样的。它们都返回一个字符串。但是 if 语句总是正确的,即使它显然是错误的!...有谁知道我做错了什么?
for (var i = 0; i < $("#slider_2011 dd").length; i++) {
if ($("#slider_2011 dd").eq(i).children("h1").text() === "text1" || "text2" || "text3"){
$("#slider_2011 dd").eq(i).children("h2").text("text4");
}
}
回答by undefined
var whiteList = ['text1', 'text2', 'text3'];
$("#slider_2011 dd").filter(function() {
return $.inArray($('h1', this).text(), whiteList) > -1;
}).find('h2').text('text4');
回答by Dipak Ingole
if ($("#slider_2011 dd").eq(i).children("h1").text() === "text1" || "text2" || "text3") // will always return true as in or(||) condition you just checked for "text1" (non negative) Which will be considered as true always.
So you should be comparing your text value like ,
所以你应该比较你的文本值,比如,
var txt = $("#slider_2011 dd").eq(i).children("h1").text();
if (txt === "text1" || txt === "text2" || txt === "text3") {
$("#slider_2011 dd").eq(i).children("h2").text("text4");
}
回答by syed imty
Your ifstatement is basically wrong. I see many have given you solution. But i want to explain you why its wrong.
你的if语句基本上是错误的。我看到很多人已经给了你解决方案。但我想向你解释为什么它是错误的。
So, you have given your if statement like this
所以,你已经给出了这样的 if 语句
if ($("#slider_2011 dd").eq(i).children("h1").text() === "text1" || "text2" || "text3")
if ($("#slider_2011 dd").eq(i).children("h1").text() === "text1" || "text2" || "text3")
javascript reads it like this
javascript 是这样读取的
if ($("#slider_2011 dd").eq(i).children("h1").text() === "text1" || true || true)
if ($("#slider_2011 dd").eq(i).children("h1").text() === "text1" || true || true)
So the condition is obviously true always.
所以条件显然总是为真。
Because javascript internally will convert the "text2" and "text3" to a boolean value. When any non empty string is converted to boolean its becomes true.
因为 javascript 在内部会将“text2”和“text3”转换为布尔值。当任何非空字符串转换为布尔值时,它变为真。
回答by pokrate
Basic flaw in if condition. Check separately for each text1, text2, text3. Get basics right.
if 条件的基本缺陷。分别检查每个 text1、text2、text3。掌握基本知识。