簡體   English   中英

當我單擊元素A時,我想更改元素B的文本

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

這個想法是,當我單擊h1.question時,h1.answer中的字符串將更改為h1.question的data-text-wap中的字符串。 例如,如果我單擊“您怎么了?”,我應該在h1.answer上看到答案“無”。

我嘗試使用.text(),但是我認為這不是正確的答案,因為我計划提出10個問題,並編寫10次.text()有點荒謬。

救命!

更新:哇! 非常感謝您的回答! 這里的所有答案都非常迅速且易於理解。 我今晚要再次看他們。 非常感謝!!

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

您將所有h1上的點擊處理程序與“問題”類綁定在一起,因此,如果您僅動態引用clicked元素,則最終會(幾乎)成為一類:

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

無需編寫text()10次...

這假定您始終只有一個“答案”元素。 如果每個問題都有一個“答案”元素,則應從$(this)obj遍歷該元素。

兩個問題:

  1. 您從$("h1.question").data(...)中丟失了$
  2. 在同一行中,要獲取單擊項的文本,請使用$(this)而不是$("h1.question")

也就是說,更改:

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

正如@AndrewL所指出的,您在這里缺少$

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

但是,您也可以只使用this來從h1.question獲取數據。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM