为什么显示更多链接仅更改h2元素而不更改<p>元素

时间:2018-10-01 19:19:18

标签: javascript jquery

这是我的Javascript代码:

<script type="text/javascript" src="http://code.jquery.com/jquery- 3.3.1.min.js"></script>
<script> 
    $(document).ready(function() {
        $("h2 + div").click(function() {
            $(this).toggleClass(".hide");
            if ($(this).attr("class") != ".hide") {
                $(this).next().hide();
            } else {
                $(this).next().show();
            }
        });
    });
</script>

这是我的HTML代码:

<main id="jdom">
    <h1>Murach's JavaScript and DOM Scripting</h1>
    <h2>Book description</h2>
    <div>
        <p>
           You can read other JavaScript books from start to finish and
           still not know how to develop dynamic websites like you want to.
           That's because it's DOM scripting that lets you do things like 
           run slide shows, handle image rollovers, rotate headlines,
           provide animation, and more. And it's a subject that's glossed
           over or ignored in most other books.
        </p>
    </div>
    <div class="hide">
        <p>
           But now, you can go from JavaScript beginner to DOM scripting 
           expert in a single book! Fast-paced, professional, and packed
           with expert practices, our new JavaScript book guides you through
           each step as you learn how to program sites that enhance the user
           experience and ensure browser compatibility.
        </p>
    </div>
    <a href="#">Show more</a>           

因此,基本上,当我启动程序时,我所能做的就是显示和隐藏h2元素。我不应该这样做,因为用户应该能够显示更多或更少的p元素。根据我在Internet上看到的内容,大多数人将其(a href)与h2元素结合在一起。我也想知道我是否也在正确使用我的切换类。

1 个答案:

答案 0 :(得分:0)

如果要使用标签(显示更多信息),建议您将标签class / id设置为a,并将其设置为hide div的class / id,例如

<a href="#" class="showmore">Show more</a>
// Javascript
$(".showmore").click(function({$(this).parent().find(".togglehide").toggleClass("hide");});

(我为.hide div设置了togglehide类)

但是如果您想使用h2 + div

$("h2 + div").click(function(){$(this).next().toggleClass("hide");});

-编辑-
抱歉,我认为您需要将show class添加到其他div并在它们之间切换。

$("#jdom").click(function() {
    $hide = $(this).find(".hide");
    $show = $(this).find(".show");
    $hide.removeClass("hide").addClass("show");
    $show.removeClass("show").addClass("hide");
});