2016-10-11 70 views
0

的文本的想法是,當我點擊h1.question,在h1.answer字符串將變爲字符串中h1.question的數據文本交換。例如,如果我點擊「你有什麼問題?」,我應該在h1.answer處看到「Nothing」的答案。當我點擊元素A,我想改變元件B

我使用的.text()嘗試,但我認爲這是不正確的答案,因爲我計劃把10個問題,寫的.text()10次是有點可笑。

幫助!

更新:哇!非常感謝答案!這裏的所有答案都非常迅速且易於理解。我今晚要再看一遍。非常感謝!!

<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

兩個問題:

  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>

1

你要綁定的所有H1與類的問題「單擊處理程序,所以如果你只是引用點擊的元素動態的,你結束了一個(幾乎)的一行:

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

不需要寫文本()的10倍......

這個假定你總是有一個確切的回答'元素。如果每個問題有「答案」元素,則應該從$(this)obj遍歷它。

0

正如@AndrewL指出的那樣,你在這裏缺少一個$

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

但是,你也可以使用this而不是從h1.question獲取數據。

$("h1.answer").text($(this).data("text-swap")); 
相關問題