javascript - 如何显示/隐藏每个文章/对象的类?

标签 javascript jquery html

我有一个非常基本的网站( http://cimoril.dothome.co.kr/greece/aegean.html ),我们正在学校进行响应式设计实践,我想为每篇文章添加一个 onClick 事件。

如何才能使其按文章而不是按类工作?例如,当我单击其中一篇文章时,我只想显示特定文章的类,而不是每篇文章。如果单击第一张图像,也会显示所有具有 .text 类的文章。

刚刚开始学习 JS/jQuery,所以我无法很好地解释,并且在谷歌搜索一段时间后未能找到答案..我提前道歉。

代码片段:

$(".text").hide();

$("article").on("click", function() {
  $("p.text").show();
});


$("article").on("mouseleave", function() {
  $("p.text").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section>
  <article>
    <div class="bg bg1">
      <span>Aghios Efstratios</span>
      <p class="text text1">Aghios Efstratios is a small Greek island southwest of Lemnos and northwest of Lesbos.</p>
    </div>
  </article>

  <article>
    <div class="bg bg2">
      <span>Chios</span>
      <p class="text text2">Chios is the fifth largest of the Greek islands, situated in the Aegean Sea</p>
    </div>
  </article>
</section>

最佳答案

您可以在点击事件中使用 this 引用来获取发生点击事件的元素。然后您就可以获取该文章元素中的段落。

顺便说一句,您不需要那么多 $(document).ready() 处理程序。您可以将它们全部归为一个(除非您有特定的理由这样做)。

例如

$(".text").hide();

$("article").click(function() {
  $(this).find("p.text").show();
});

$("article").mouseleave(function() {
  $(this).find("p.text").hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <article>
    <div class="bg bg1">
      <span>Aghios Efstratios</span>
      <p class="text text1">Aghios Efstratios is a small Greek island southwest of Lemnos and northwest of Lesbos.</p>
    </div>
  </article>

  <article>
    <div class="bg bg2">
      <span>Chios</span>
      <p class="text text2">Chios is the fifth largest of the Greek islands, situated in the Aegean Sea</p>
    </div>
  </article>
  <section>

关于javascript - 如何显示/隐藏每个文章/对象的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45180091/

相关文章:

javascript - React Native 不渲染 prop 更改

基于比较子元素内容与目标标题内容的 Javascript 对元素进行排序

jquery - 指向上层的 href

javascript - 从外部 <form> 标签获取表单对象

javascript - 在执行了一些 javascript 指令后,如何加载 html 文档?

c# - 将值从代码隐藏传递到 JavaScript 函数

javascript - 如何将选择值获取到 Controller 中

javascript - 如何让javascript创建的html元素出现在页面顶部?

jQuery 警告框固定位置问题?

javascript - Azure 移动服务 HTML 5 用户身份验证在 IE(.NET 后端)中显示 Windows 安全对话框