2016-10-11 2 views
0

考え方は、h1.questionをクリックすると、h1.questionの文字列がh1.questionのdata-text-swapの文字列に変更されるという考えです。たとえば、「あなたに何が問題なの?」をクリックすると、h1.answerに「何もない」という回答が表示されます。要素Aをクリックすると要素Bのテキストを変更したい

私は10文字の質問を書いて.text()を10回書くことはちょっとばかげているので、.text()を使ってみましたが正しい答えではないと思います。

ヘルプ!

更新:うわー!回答ありがとうございました!ここの答えはすべて本当に素早く理解しやすいものです。私は今夜​​再び彼らを見るつもりです。本当にありがとう!!あなただけ動的にクリックされた要素を参照する場合、あなたは(ほとんど)ワンライナーで終わるので、あなたは、すべてのクラスでh1を「質問」をクリックハンドラをバインドしている

<h1 class="answer">Answer here</h1></div> 
<h1 class="question" data-text-swap="Nothing">What is wrong with you?</h1> 
<h1 class="question" data-text-swap="Good!">How is the weather today?</h1> 
<h1 class="question" data-text-swap="Everything">What is wrong with him?</h1> 


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 

<script> 
$("h1.question").click(ontop); 
    function ontop() { 
    $("h1.answer").text(("h1.question").data("text-swap")); 
} 
</script> 
+1

'h1.question'セレクタにドル記号がありません。 – Li357

答えて

1

2つの問題:

  1. あなたがクリックした項目のテキストであることを代わりに$("h1.question")

$(this)を使用し得るために、同じラインで$("h1.question").data(...)

  • から$が欠落しています、変更:

    $("h1.answer").text(("h1.question").data("text-swap")); 
    

    へ:

    文脈では
    $("h1.answer").text($(this).data("text-swap")); 
    

    $("h1.question").click(ontop); 
     
    function ontop() { 
     
        $("h1.answer").text($(this).data("text-swap")); 
     
    }
    <h1 class="answer">Answer here</h1></div> 
     
    <h1 class="question" data-text-swap="Nothing">What is wrong with you?</h1> 
     
    <h1 class="question" data-text-swap="Good!">How is the weather today?</h1> 
     
    <h1 class="question" data-text-swap="Everything">What is wrong with him?</h1> 
     
    
     
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

  • 1

    $('h1.question').on('click', function() { 
        $('h1.answer').text($(this).attr('data-text-swap')); 
    }); 
    

    テキストを書く必要はありません。()10回...

    これは常に1つの「回答」要素が常にあることを前提としています。質問ごとに「回答」要素がある場合は、$(this)objからその項目に移動する必要があります。

    0

    としては、ここで$が欠落している、@AndrewLが指摘:

    $("h1.answer").text(("h1.question").data("text-swap")); 
            ^
    

    しかし、あなたちょうどを使用することもできます代わりに3232を使用して、h1.questionからデータを取得します。

    $("h1.answer").text($(this).data("text-swap")); 
    
    関連する問題