这个想法是,当我点击 h1.question 时,h1.answer 中的字符串将更改为 h1.question 的 data-text-swap 中的字符串。例如,如果我点击“你怎么了?”,我应该在 h1.answer 中看到答案“没什么”。
我尝试过使用 .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>
最佳答案
两个问题:
- 您缺少
$("h1.question").data(...)
中的$
- 在同一行中,要获取单击项目的文本,请使用
$(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>
关于javascript - 当我单击元素 A 时,我想更改元素 B 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39970480/