Cannot get === string.length to work correctly

时间:2016-06-23 18:16:41

标签: javascript jquery

I have code that checks if a user has entered text into an input field. If the field is empty I want to display: you have not started.

If the field has a length greater than 1 - I want to display: you've finished. My code below works for determining when the user is finished but displays nothing saying you have not started. Any thoughts? Thanks!

HTML:

<p id="progressDisplay"> </p>



<p id="response"> </p>
<p id="response2"> </p>

JS:

var progress =($("#progressDisplay").text());


if( progress.length === 0 ){
    $("#response2").text("You have not entered anything yet")
}

if( progress.length > 1){
    $("#response").text("You've Finished this section")
}

3 个答案:

答案 0 :(得分:6)

元素中的空格包含在其文本值中。您的元素以单个空格字符开头,因此它始终具有length > 0

修剪文字以避免空格,因为您可以使用原生JavaScript String#trim 方法。

var progress = $("#progressDisplay").text().trim();

或使用 jQuery.trim() 方法。

var progress = $.trim($("#progressDisplay").text());

答案 1 :(得分:0)

这是因为在<p>中你有空格:

  

<p id="progressDisplay"> </p>

此空格将计为文本,并在获取段落的.text()时被选中。

更好的方法是手动删除空格或使用不包含空格的.trim()方法。

此外,还有一点比较:

===

比较变量的type以及它的值。例如:

2 === 2 true
2 === "2" false (因为一个是整数,一个是字符串)

如果您不想比较类型而只想比较值,请使用:==

答案 2 :(得分:-1)

为什么不使用别的?请参阅小提琴https://jsfiddle.net/6cge9rLb/

if( progress.length > 1){
    $("#response").text("You've Finished this section")
}else{
    $("#response2").text("You have not entered anything yet")
}