我想分别对两个按钮应用切换功能。但是,当我使用下面的代码时,它会切换每个按钮下的两个内容。我怎样才能将它们分开,以便在我单击第一个按钮时仅切换其下方的内容?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
<script>
$("button").click(function () {
$("p").toggle();
});
</script>
</body>
</html>
最佳答案
简单:使用nextUntil()
。
将选择所有下一个元素,直到到达匹配的元素(在您的情况下是下一个按钮
):
jsFiddle demo
$("button").click(function () {
$(this).nextUntil('button').toggle();
});
关于javascript - .toggle() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11507989/