2

置換変数 (localStorage 内) が見つからない場合、次のスクリプトが Value 属性をそのままにするのではなく完全に削除するという、非常に奇妙なバグです。

私のHTML:

<form>
<input class="xfield" type="hidden" name="source" value="x111" />
</form>

JS

<script>

     var thecode = localStorage.getItem("xcode");
     if (thecode != "undefined" && thecode != "null") {
      $(".xfield").attr("value",thecode);
}

</script>

基本的に、xcode アイテムが localStorage で見つかった場合、すべてがうまく機能し、デフォルト値が置き換えられます。ただし、xcode が localStorage に見つからない場合、その結果 (Chrome のみのようですが、Firefox は正常に動作し、デフォルトのままになります) は、value 属性が完全に消去されます。

.prop代わりに使用したり、ラップしたりしてみまし$(window).load(function(){たが、何も機能しません。ここで何が間違っているのでしょうか?

4

2 に答える 2

3

なぜなら"underfined" !== undefined、そして"null" != null

if (thecode!==null) {
    $(".xfield").val(thecode);
}
于 2014-10-09T17:02:11.980 に答える
1

あなたの目標がundefinedまたはをチェックすることである場合は、またはではなくおよび(どちらでもない)nullをチェックします。:-)undefinednull"undefined""null"undefinednull

var thecode = localStorage.getItem("xcode");
if (thecode != undefined) { // Loose != works for both undefined and null
    $(".xfield").attr("value",thecode);
}

ただしgetItem、返されませんundefined(キーが存在しない場合は返す必要がnullあり、存在する場合は文字列 [またはキャンバスなどの他の保存可能なもの] を返す必要があります)、次のようになります。

var thecode = localStorage.getItem("xcode");
if (thecode !== null) {
    $(".xfield").attr("value",thecode);
}

気になる場合にコードが常に空白ではない場合は、thecode直接テストすることができます:

var thecode = localStorage.getItem("xcode");
if (thecode) {
    $(".xfield").attr("value",thecode);
}

それはそれを真実の値に設定します。undefinednull、および""はすべて誤りです ( 0NaN、および とfalse同様ですが、 からそれらを取得することはできませんgetItem)。

于 2014-10-09T17:03:06.970 に答える