.toggle() function

.toggle() function

本文关键字:function toggle      更新时间:2023-11-04

我想将toggle函数分别应用于这两个按钮。然而,当我使用下面的代码时,它会在每个按钮下切换两个内容。我如何将它们分开,以便当我单击第一个按钮时,只有它下面的内容才会被切换?

<!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()
将选择所有下一个元素,直到达到匹配的元素(在您的情况下是下一个button):

jsFiddle演示

$("button").click(function () {
     $(this).nextUntil('button').toggle();
});

试试这个:

$("button").click(function () {
  $(this).nextAll("p:lt(2)").toggle();
});

http://jsbin.com/orujav

为什么有两个段落标记?制作您的HTML:

<button>Toggle</button>
<p>Hello</p>
<button>Toggle</button>
<p>Hello</p>

和您的jQuery:

$("button").click(function () {
    $(this).next('p').html( ($(this).next('p').html()=='Hello')?'Good Bye':'Hello');
});​

jsFiddle示例