我在选择 DOM 中的某些元素时遇到问题。我正在尝试做的是切换 div 的类以使用链接显示和隐藏内容,然后将链接文本与其一起更改。
我的代码现在同时影响所有链接和 div,这当然不是我想要的。我希望链接上方的 div 以及“显示更少”的链接文本受到影响。下面是 HTML 和 jQuery。
<body>
<section id="jdom">
<h1>Murach's JavaScript and DOM Scripting</h1>
<h2>Book description</h2>
<div>
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.</p>
</div>
<div class="hide">
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.</p>
</div>
<a href="#">Show more</a>
<h2>About the author</h2>
<div>
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</p>
</div>
<div class="hide">
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.</p>
</div>
<a href="#">Show more</a>
<h2>Who this book is for</h2>
<div>
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.</p>
</div>
<div class="hide">
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.
</div>
<a href="#">Show more</a>
</section>
</body>
我的jQuery
$(document).ready (function () {
$("a").toggle (
function() {
$("div").toggleClass();
$("a").text("Show less");
},
function() {
$("div").toggleClass();
$("a").text("Show more");
}
); //end toggle
}); //end ready