JQuery Auto Read More和Read Less问题

时间:2012-09-07 18:00:46

标签: jquery click nested append

我正在尝试创建一个自动阅读更多内容并阅读更少,只需在文本中的任何位置弹出<a href="#" class="readmore">YOUR TEXT"</a>并遇到问题。现在它几乎可以工作,但是如果你打开几个不同的readmore然后点击页面关闭的所有readlesses无读。有任何想法吗?下面的所有代码都带有注释。

// Auto Readmore with a link that has the readmore class
$(document).ready(function() {
    // Show Read more link that is hidden by css
    $('.readmore').show("fast");
    // Loop through all  .readmores
    $('a.readmore').each(function(index) {
        // Set the Node of the link
        var currentreadmore = $(this);
        // set the id to the index of the each
        $(this).attr('id', 'readmore-' + index);
        var node = currentreadmore[0];
        if (node && node.nextSibling) {
            // if not at the end of a paragraph remove the rest of the paragraph and append ...
            var afternodecontent = node.nextSibling.nodeValue;
            node.nextSibling.nodeValue = " ...";
        }
        // hide everything after the readmore link
        $(this).parent().nextAll().hide();

        // create click function to append the rest of the paragraph and show the content. Also hides the readmore button
        $(this).click(function() {
            // add the content back in
            if (node && node.nextSibling) node.nextSibling.nodeValue = afternodecontent;
            // hide the content
            $(this).parent().nextAll().slideToggle("slow");
            // hide the read more button
            $(this).hide("slow");

            // add the readless button
            $(this).parent().nextAll().last().append('<p id="readless-' + index + '" class="readless-wrapper"><a href="#" class="readless">Read Less...</a></p>');    

            // hvea the readless button click work
            $('.readless').click(function() {
                // show the readmore info based off of the index of the button
                $('#readmore-' + index).parent().nextAll().slideToggle("slow");

                // show the read more
                $('#readmore-' + index).show("slow");

                // append the ... and hide the rest of the content
                if (node && node.nextSibling) {
                    // if not at the end of a paragraph remove the rest of the paragraph and append ...
                    var afternodecontent = node.nextSibling.nodeValue;
                    node.nextSibling.nodeValue = " ...";
                }

                // remove the readless button
                $('.readless-wrapper').remove();

                // stop the href
                return (false);
            });
            // stop the href from working
            return (false);

        }); // Close Click function
    }); // Close Each Function
}); // Close document ready

0 个答案:

没有答案