javascript - 当我单击元素 A 时,我想更改元素 B 的文本

标签 javascript jquery

这个想法是,当我点击 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>

最佳答案

两个问题:

  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>

关于javascript - 当我单击元素 A 时,我想更改元素 B 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39970480/

相关文章:

javascript - JQuery - 无法识别动态元素

javascript - Jquery 插件不验证表单

javascript - 无法使用 javascript 删除和显示另一个 ul 标签?

javascript闭包局部变量超出范围?

javascript - 我该如何完成这个循环?连接前面的两个字符

javascript - 随着用户不断输入,动态增加文本区域高度(没有滚动条)

Javascript setInterval 连续多行

javascript - jsplumb 中标签的重叠

javascript - 将日期从 gergorian 转换为 shamsi

javascript - 定义自定义服务的语法