2017-01-03 5 views
-1

を働いていない私はこのコードを持っている:Javascriptを==「は」右

$(document).ready(function() { 
 
    $('#search').keyup(function() { 
 
    var search = $('#search').val(); 
 
    console.log(search); 
 
    if (search.length !== 0 || search !== "") { 
 
     $('.wrapper').css({ 
 
     "background-color": "#000", 
 
     "opacity": 0.8 
 
     }); 
 
     $('.post').remove(); 
 
    } else { 
 
     location.reload(false); 
 
    }; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form action="#"> 
 
    <button type="submit">Search</button> 
 
    <input type="text" name="search" id="search" /> 
 
</form>

をしかし、問題は、入力要素で先頭に何でも置くスペース、機能がないということです働いています(それは$('.wrapper').css({"background-color":"#000","opacity":0.8}); and $('.post').remove();を実行します)。

+2

チェックアウト 'search.trim()!== '''。 – trincot

+0

ちょうどヒントですが、あなたはif条件を 'if(search){'と置き換えることができます –

+0

* "input要素の先頭にスペースを入れる"とは何ですか?あなたはスペースを入力することを意味します(input要素の値として)? –

答えて

0

使用String#trimテキストの前後にスペースを削除するには:

var search = $('#search').val().trim(); 

$(document).ready(function() { 
 
    $('#search').keyup(function() { 
 
    var search = $('#search').val().trim(); 
 

 
    if (search) { 
 
     $('.wrapper').css({ 
 
     "background-color": "#000", 
 
     "opacity": 0.8 
 
     }); 
 
     $('.post').remove(); 
 
    } else { 
 
     location.reload(false); 
 
    }; 
 

 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form action="#"> 
 
    <button type="submit">Search</button> 
 
    <input type="text" name="search" id="search" /> 
 
</form>

0

単に使用!または!!空の文字列を確認する:

1

条件の前にsearch = search.trim();を追加するだけです。

searchにスペースを追加するときはではなく''ですので、trimが必要です。使用してさらに

、:

if (search) { 
    .... 
} 

代わりの

if (search.length !== 0 || search !== '') { 
    ... 
} 

はあなたにこのケースでも同じ結果が得られますシンプルなチェックです。 ''0の両方が'falsey'です。

$(document).ready(function() { 
 
    $('#search').keyup(function() { 
 
    var search = $('#search').val(); 
 
    search = search.trim(); //Try adding this line 
 
    console.log(search); 
 
    if (search.length !== 0 || search !== "") { 
 
     $('.wrapper').css({ 
 
     "background-color": "#000", 
 
     "opacity": 0.8 
 
     }); 
 
     $('.post').remove(); 
 
    } else { 
 
     location.reload(false); 
 
    }; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form action="#"> 
 
    <button type="submit">Search</button> 
 
    <input type="text" name="search" id="search" /> 
 
</form>

関連する問題