jQuery remove()和其他方法工作一次,但相同的代码不能反向工作

时间:2021-09-17 12:27:41

This is a little long, so stay with me. At the request of my teacher, I'm building a pile of text, some of which is hidden, and I want to add a "more" text at the end. When clicking it, that line is removed and replaced with a "less" text, the hidden text is revealed, and if I click the "less" text it reverts to the original position. Here's what I have so far:

这有点长,所以和我在一起吧。应老师的要求,我正在构建一堆文本,其中一些是隐藏的,我想在最后添加一个“更多”的文本。单击它时,该行将被删除并替换为“less”文本,隐藏文本将被显示,如果单击“less”文本,它将恢复到原始位置。这是我到目前为止所拥有的:

<p>
            The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<br /><br />
            <span class="hidden">
                None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br /><br />
                While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br /><br />
                This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br /><br />
                The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br /><br />
                In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br /><br />
                This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc. <br /><br />
                I hope you enjoy this updated version, as much as I enjoyed working on it.
            </span>
        </p>

And the Jquery commands:

和Jquery命令:

    $("span.hidden").ready(function () {
    var more = "<p class=\"click\" display=\"inline\">[...more]</p>";
    var less = "<p class=\"clicked\" display=\"inline\">[...less]</p>";
    if ($("span.hidden").css('display') == "none") {
        $(more).insertAfter("span.hidden");
    }
    else {
        $(less).insertAfter("span.unhidden");
    }

    $(".click").click(function () {
        $("span.hidden").toggleClass("unhidden");
        $("span.hidden").toggleClass("hidden");
        $(less).insertAfter("span.unhidden");
        $("p").remove(".click");
    });

    $(".clicked").click(function () {
        $("span.unhidden").toggleClass("hidden");
        $("span.unhidden").toggleClass("unhidden");
        $(more).insertAfter("span.hidden");
        $("p").remove(".clicked");
    });
});

Now here's the weird part: the functions work perfectly until the last one. The "more" is added, when I click it it is replaced by the "less" and the span is revealed... But the last function, which is identicle to the previous on in every way except the class names, doesn't work! I have checked the html DOM using F12 in chrome, and all the classes indeed change as they should after the second function, but nothing happens when I press the "less" text...

现在这里是奇怪的部分:功能完美地工作到最后一个。添加“更多”,当我点击它时,它被“less”替换,并且显示了span ...但是最后一个函数,除了类名之外,在各方面都与前一个函数相同,不会工作!我在chrome中使用F12检查了html DOM,并且所有类确实在第二个函数之后发生了变化,但是当我按下“less”文本时没有任何反应...

Any ideas what I'm doing wrong?

我有什么想法我做错了吗?

Thanx for the help!

Thanx的帮助!

3 个解决方案

#1


0  

You can use: 'jQuery plugin to automatically shorten text in a DIV and add "show more" link.'

您可以使用:'jQuery插件自动缩短DIV中的文本并添加“显示更多”链接。

Working example: JSFiddle

工作示例:JSFiddle


Step 1: Include the jQuery plugin in your HTML

第1步:在HTML中包含jQuery插件

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/viralpatel/jquery.shorten/master/src/jquery.shorten.js"></script>

Step 2: Add the code to shorten any DIV content (we are shortening DIV with class 'text')

第2步:添加代码以缩短任何DIV内容(我们用类'text'缩短DIV)

<p class="text">
The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<br /><br />
None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br /><br />
While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br /><br />
This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br /><br />
The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br /><br />
In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br /><br />
This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc.<br /><br />
I hope you enjoy this updated version, as much as I enjoyed working on it.
</p>

Step 3: You may want to pass the parameters to shorten() method and override the default ones on jQuery.

第3步:您可能希望将参数传递给shorten()方法并覆盖jQuery上的默认参数。

$(function() {

    $(".text").shorten({
        "showChars" : 200
    });

    // OR
    $(".text").shorten({
        "showChars" : 150,
        "moreText"  : "See More",
    });

    // OR
    $(".comment").shorten({
        "showChars" : 50,
        "moreText"  : "See More",
        "lessText"  : "Less",
    });

});

#2


1  

Did you try re-adding the classes? i.e.

你尝试重新添加课程了吗?即

after removing click, try adding clicked and conversely

删除点击后,尝试添加点击,反之亦然

after removing clicked, add click

删除点击后,添加点击

#3


1  

You don't need to remove and add any DOM elements to achieve this functionality.

您无需删除和添加任何DOM元素即可实现此功能。

Simply use JQuerys .toggle() function do show and hide the text. Also, when clicked, just change the text of the "button".

只需使用JQuerys .toggle()函数即可显示和隐藏文本。此外,单击时,只需更改“按钮”的文本。

Solution using .each()

使用.each()的解决方案

Working example: JSFiddle

工作示例:JSFiddle

HTML

<p class="moreOrLessText">
    The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<span class="moreText"><br />
    <br />None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br />
    <br />
    While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br />
    <br />
    This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br />
    <br />
    The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br />
    <br />
    In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br />
    <br />
    This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc. <br />
    <br />
    I hope you enjoy this updated version, as much as I enjoyed working on it.</span> <a class="moreLess">[...more]</a>
</p>

<p class="moreOrLessText">
    The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<span class="moreText"><br />
    <br />None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br />
    <br />
    While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br />
    <br />
    This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br />
    <br />
    The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br />
    <br />
    In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br />
    <br />
    This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc. <br />
    <br />
    I hope you enjoy this updated version, as much as I enjoyed working on it.</span> <a class="moreLess">[...more]</a>
</p>

CSS

.moreLess {
    cursor: pointer;
}

.moreText {
    display: none;
}

JQuery

$(function() {

    $('.moreOrLessText').each(function() {

        var self = $(this),
            moreLessButton = self.find('.moreLess'),
            moreText = self.find('.moreText');

        moreLessButton.click(function() {

            moreText.stop().toggle();

            if(moreText.is(':visible')) {

                moreLessButton.text('[...less]');

            }
            else {

                moreLessButton.text('[...more]');

            }

        });

    });

});

Solution not using .each()

解决方案不使用.each()

Working example: JSFiddle

工作示例:JSFiddle

JQuery

$(function() {

    $('.moreLess').click(function() {

        var self = $(this),
            moreText = self.siblings('.moreText');

        moreText.stop().toggle();

        if(moreText.is(':visible')) {

            self.text('[...less]');

        }
        else {

            self.text('[...more]');

        }

    });

});

Also, have a look at the .find(), .siblings(), .stop() (not really necessary here since it's not animating), .text() and .is() functions I've used here.

另外,看一下.find(),. siblings(),. stop()(这里不是真的必要,因为它不是动画),我在这里使用的.text()和.is()函数。

There are a couple of more toggle functions which can be used to animate the showing and hiding the text. See .slideToggle() and .fadeToggle()

还有一些切换功能可用于动画显示和隐藏文本。请参阅.slideToggle()和.fadeToggle()

#1


0  

You can use: 'jQuery plugin to automatically shorten text in a DIV and add "show more" link.'

您可以使用:'jQuery插件自动缩短DIV中的文本并添加“显示更多”链接。

Working example: JSFiddle

工作示例:JSFiddle


Step 1: Include the jQuery plugin in your HTML

第1步:在HTML中包含jQuery插件

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/viralpatel/jquery.shorten/master/src/jquery.shorten.js"></script>

Step 2: Add the code to shorten any DIV content (we are shortening DIV with class 'text')

第2步:添加代码以缩短任何DIV内容(我们用类'text'缩短DIV)

<p class="text">
The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<br /><br />
None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br /><br />
While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br /><br />
This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br /><br />
The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br /><br />
In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br /><br />
This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc.<br /><br />
I hope you enjoy this updated version, as much as I enjoyed working on it.
</p>

Step 3: You may want to pass the parameters to shorten() method and override the default ones on jQuery.

第3步:您可能希望将参数传递给shorten()方法并覆盖jQuery上的默认参数。

$(function() {

    $(".text").shorten({
        "showChars" : 200
    });

    // OR
    $(".text").shorten({
        "showChars" : 150,
        "moreText"  : "See More",
    });

    // OR
    $(".comment").shorten({
        "showChars" : 50,
        "moreText"  : "See More",
        "lessText"  : "Less",
    });

});

#2


1  

Did you try re-adding the classes? i.e.

你尝试重新添加课程了吗?即

after removing click, try adding clicked and conversely

删除点击后,尝试添加点击,反之亦然

after removing clicked, add click

删除点击后,添加点击

#3


1  

You don't need to remove and add any DOM elements to achieve this functionality.

您无需删除和添加任何DOM元素即可实现此功能。

Simply use JQuerys .toggle() function do show and hide the text. Also, when clicked, just change the text of the "button".

只需使用JQuerys .toggle()函数即可显示和隐藏文本。此外,单击时,只需更改“按钮”的文本。

Solution using .each()

使用.each()的解决方案

Working example: JSFiddle

工作示例:JSFiddle

HTML

<p class="moreOrLessText">
    The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<span class="moreText"><br />
    <br />None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br />
    <br />
    While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br />
    <br />
    This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br />
    <br />
    The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br />
    <br />
    In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br />
    <br />
    This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc. <br />
    <br />
    I hope you enjoy this updated version, as much as I enjoyed working on it.</span> <a class="moreLess">[...more]</a>
</p>

<p class="moreOrLessText">
    The original Wheel of Time RPG was released in 2001 under the D20 rules. This website was built while Dungeons and Dragons' 5th edition (also known as D&D Next) is only days after release. These restrictions made it difficult to adopt some of the larger aspects of the game, such as prestige classes, feats and skills.<span class="moreText"><br />
    <br />None the less, this document presents an attempt to balance between the D&D 5th edition rules and the Wheel of Time universe as presented in both the Wheel of Time series by Robert Jordan and the Wheel of Time Roleplaying Game.<br />
    <br />
    While using terms and general mechanics, this document does not include the rules of the D&D system. In order to understand how combat, weave slots, etc. work, you need to purchase the D&D 5th edition Player’s Handbook.<br />
    <br />
    This document also does not explain many of the terms, cultures, geography, etc. of the Wheel of Time. Most of what you need to know is described in the Wheel of Time Roleplaying Game sourcebook.<br />
    <br />
    The system adopted to accommodate the new D&D rules was to incorporate most Prestige Classes in the Wheel of Time Roleplaying Game as paths that the characters may follow. In many cases, I found this system actually resembles the Wheel of Time series better than the original source book. For example, we were able to incorporate the One Power Traditions to the Initiate, depending on her origin.<br />
    <br />
    In other cases, more drastic changes were made. If you are playing a channeler, make sure to read through the entire Channeling chapter, since many changes were made to the channeling system. For example, Power Heightened Senses no longer requires a feat. It is a feature every channeler receives the moment he touches the One Power.<br />
    <br />
    This document is far from a complete overhaul. The GM is still required to adjust many technical and numerical details from the original RPG, such as monster, NPC statistics, certain types of weapons and equipment, etc. <br />
    <br />
    I hope you enjoy this updated version, as much as I enjoyed working on it.</span> <a class="moreLess">[...more]</a>
</p>

CSS

.moreLess {
    cursor: pointer;
}

.moreText {
    display: none;
}

JQuery

$(function() {

    $('.moreOrLessText').each(function() {

        var self = $(this),
            moreLessButton = self.find('.moreLess'),
            moreText = self.find('.moreText');

        moreLessButton.click(function() {

            moreText.stop().toggle();

            if(moreText.is(':visible')) {

                moreLessButton.text('[...less]');

            }
            else {

                moreLessButton.text('[...more]');

            }

        });

    });

});

Solution not using .each()

解决方案不使用.each()

Working example: JSFiddle

工作示例:JSFiddle

JQuery

$(function() {

    $('.moreLess').click(function() {

        var self = $(this),
            moreText = self.siblings('.moreText');

        moreText.stop().toggle();

        if(moreText.is(':visible')) {

            self.text('[...less]');

        }
        else {

            self.text('[...more]');

        }

    });

});

Also, have a look at the .find(), .siblings(), .stop() (not really necessary here since it's not animating), .text() and .is() functions I've used here.

另外,看一下.find(),. siblings(),. stop()(这里不是真的必要,因为它不是动画),我在这里使用的.text()和.is()函数。

There are a couple of more toggle functions which can be used to animate the showing and hiding the text. See .slideToggle() and .fadeToggle()

还有一些切换功能可用于动画显示和隐藏文本。请参阅.slideToggle()和.fadeToggle()