jQuery 如何使每个 <li> 与 <ul> 切换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15163719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make each <li> toggle with <ul>
提问by user2122032
How can I make just one <li>
toggle per <ul>
. What is happening with this code is that all <ul>
tags are being rendered. which also renders all the <li>
tags. I want one <li>
to toggle when its corresponding <ul>
is clicked on.
我怎样才能让<li>
每个<ul>
. 这段代码发生的事情是所有<ul>
标签都被渲染。它还呈现所有<li>
标签。我想要一个<li>
在<ul>
点击相应的时切换。
code:
代码:
<script>
$(document).ready(function(){
$("ul").click(function(){
$("li").toggle();
});
});
</script>
<body>
<ul>Toggle between hide() and show()</ul>
<li>This is a paragraph.</li>
<ul>Toggle between hide() and show()</ul>
<li>This is a paragraph.</li>
<body/>
回答by Adil
Add the current event source as context, also put li
in ul
.
添加当前事件源的情况下,也把li
在ul
。
Html
html
<ul>Toggle between hide() and show()
<li>This is a paragraph.</li>
</ul>
<ul>Toggle between hide() and show()
<li>This is a paragraph.</li>
</ul>
Javascript
Javascript
$(document).ready(function(){
$("ul").click(function(){
$("li", this).toggle();
});
});
Edit:To toggle on when ul is click but not li
编辑:单击 ul 而不是 li 时打开
$(document).ready(function () {
$("ul").click(function (evt) {
if(evt.target.tagName != 'UL')
return;
$("li", this).toggle();
});
});
回答by freakish
$("ul").click(function(){
$(this).find("li").toggle();
});
and move li
's inside ul
:
和 moveli
的里面ul
:
<ul>
<li>This is a paragraph.</li>
</ul>
Actually you should entirely refactor your HTML, because it doesn't make any sense ( and it is invalid ). But JavaScript code ( which triggers something inside something else ) is like the one above.
实际上你应该完全重构你的 HTML,因为它没有任何意义(而且它是无效的)。但是 JavaScript 代码(触发其他东西内部的东西)就像上面的代码。
回答by Fellipe Soares
If you have only one li
you don't need a ul
.
The .toggle()
function is deprecated in jQuery 1.8.
如果您只有一个li
,则不需要ul
. 该.toggle()
函数在 jQuery 1.8 中已弃用。
Try this:
尝试这个:
$(".trigger").click(function(){
var obj = $(this).next();
if($(obj).hasClass("hidden")){
$(obj).removeClass("hidden").slideDown();
} else {
$(obj).addClass("hidden").slideUp();
}
});
HTML:
HTML:
<div class="trigger">Toogle</div>
<div class="elem hidden">Content</div>
<div class="trigger">Toogle</div>
<div class="elem hidden">Content</div>
CSS:
CSS:
.elem { display:none; }
See demo here: DEMO
在此处查看演示:DEMO