简体   繁体   中英

When I click Element A, I want to change text of Element B

The idea is that when I click on h1.question, the string in h1.answer will change to the string in h1.question's data-text-swap. For example, if I click "What is wrong with you?", I should see the answer "Nothing" at h1.answer.

I've tried using .text() but I think it isn't the right answer because I plan to put 10 questions and writing .text() 10 times is a bit ridiculous.

Help!

Update: Wow! Thanks so much for the answers! All the answers here have been really swift and easy to understand. I'm going to look at them again tonight. Thanks so much!!

<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>

you are binding the click handler on all h1 with class 'question', so if you just reference the clicked element dynamically, you end up with a (almost) one-liner:

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

no need to write text() 10 times...

this assumes that you always have exactly one 'answer' element. if you have an 'answer' element per question, you should traverse to it from the $(this) obj.

Two problems:

  1. You are missing the $ from $("h1.question").data(...)
  2. In that same line, to get the text of the clicked item use $(this) instead of $("h1.question")

That is, change:

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

To:

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

In context:

 $("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> 

As pointed out by @AndrewL, you are missing a $ here:

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

But, you could also just use this instead to get the data from h1.question .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM