使用jquery...
我试图点击一个术语或概念来查看定义(我的列表项)。当我单击定义时,我希望将其替换为术语或概念。
我尝试使用唯一 ID 来分隔每个 p 和 li,使它们分别响应点击。我在我的 html 中添加了一个 href= "#"使每个列表项成为一个可以点击的链接。
但是,当我运行代码时,点击同时对所有四个“java-showing”和“java-hiding”div 进行操作。这导致页面仅在前两个列表项“JavaScript (JS), & Operators”和 JavaScript 的定义“面向对象的...”之间切换。
首先,为什么我在点击时只得到一个定义?我希望 2...
如果有人能帮助我,那就太好了,我对 Javascript、html、css 非常陌生。
//HTML
<body>
<ul>
<div class ="java-hiding">
<li id="li1" <a href="#"> JavaScript (JS)</a></li>
</div>
<div class ="java-showing">
<p id="p1" <a href="#">An object-oriented computer programming language commonly used to create interactive effects within web browsers.</a></p>
</div>
<div class="java-hiding">
<li id="li2" <a href="#">Operators</a></li>
<div class ="java-showing">
<p id ="p2" <a href="#">constructs which behave generally like functions, but which differ syntactically or semantically from usual functions</a></p>
</div>
</ul>
//Java脚本
$(document).ready(function() {
$("li#li1, p#p1, li#li2, p#p2").click(function() {
$(".java-showing").toggle();
$(".java-hiding").toggle();
});
});
///CSS
.java-showing { display:none; }
最佳答案
您的 Html 结构不合理,因为您的类名相同,事件将对预期的所有元素进行操作。
此外,您不必为每个元素添加 Id 即可实现您的功能。
您是否正在寻找这样的行为 - FIDDLE
<div class ="java-hiding">
<li id="li1"><a href="#"> JavaScript (JS)</a></li>
</div>
<div class ="java-showing">
<p id="p1">
<a href="#">An object-oriented computer programming language commonly used to create interactive effects within web browsers.</a>
</p>
</div>
<div class="java-hiding">
<li id="li2"> <a href="#">Operators</a></li>
</div>
<div class ="java-showing">
<p id ="p2">
<a href="#">constructs which behave generally like functions, but which differ"#">constructs which behave generally like functions, but which differ syntactically or semantically from usual functions</a>
</p>
</div>
J查询:
$(document).ready(function() {
$("li").click(function() {
$(this).parent().next().toggle();
});
$("p").click(function() {
$(this).parent().toggle();
});
});
关于javascript - 使用 JavaScript 切换 html 列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46188504/