2017-03-23 2 views
0

divでdivになり、そのdivのテキストを "Sold out"に変更する単純なスクリプトを作成しようとしています。ただし、.textは「売り切れ」ではなく、[Object, Object]を返しています。私が間違っていることを誰かが教えてくれれば、とても感謝しています。前もって感謝します。jQuery - .textは、変数の代わりに[Object Object]を返します。

敬具、ジョージ

$(function Store(){ 
 

 
    Status = "Sold out"; 
 
    
 
    $("div").each(function(){ 
 
     $(this).contents().not($(this).children()).text(Status); 
 
     alert($(this).contents().not($(this).children()).text(Status)); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 

 
<div id="Wallet"> 
 
    <div class="Price"> 
 
     10.00$ 
 
    </div> 
 
    <div class="Price"> 
 
     20.00$ 
 
    </div> 
 
    <div class="Price"> 
 
     30.00$ 
 
    </div> 
 
</div>

+0

「売り切れ」という警告を表示したい場合は、それを直接警告するだけではどうですか? – Pytth

+0

@Pytth明らかに、彼の実際の仕事は簡略化されています。そこではテキストは可変です。 – Barmar

答えて

3

あなたは.text()に引数を与えた場合、それはテキストを返しません、それはテキストを設定します。そして、メソッドが連鎖できるようにjQueryオブジェクトを返します。

テキストを表示する場合は、引数を省略してください。

$(function Store(){ 
 

 
    Status = "Sold out"; 
 
    
 
    $("div").each(function(){ 
 
     $(this).contents().not($(this).children()).text(Status); 
 
     alert($(this).contents().not($(this).children()).text()); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 

 
<div id="Wallet"> 
 
    <div class="Price"> 
 
     10.00$ 
 
    </div> 
 
    <div class="Price"> 
 
     20.00$ 
 
    </div> 
 
    <div class="Price"> 
 
     30.00$ 
 
    </div> 
 
</div>

これは、しかし、Sold outに警告されていません。これは、.text(Status)がテキストノードのテキストを設定できないためだと思います。可能であれば、.contents()を使用してテキストノードにアクセスするのではなく、Sold outメッセージを入力する<div>または<span>のメッセージを表示するようにHTMLを再設計する必要があります。

関連する問題