我有一个非常基本的网站( 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/