从dataBase加载整个数据后,Jquery(读取更多/读取更少)不起作用

时间:2015-04-07 18:31:21

标签: javascript php jquery ajax

我正在尝试使用从数据库加载的数据来创建“Read more / Read less”功能。

我的jQuery函数非常适用于我的HTML页面中已存在的数据,但不适用于从数据库加载的数据。

我的代码:

<body>    
    <div class="slider ">

                 <?php 
         //connexion to data base config

                     while ( /* condition */)
                        {
                            //other config      
                     ?>

              <div class="w-slide news-slide">
              <p class="article-text-style"> 
                    <?php         
                       news_affiche_fiche($newsId);
                    ?>

               </p>

               </div>

                    <?php  
                        }    
                    ?>

                <div class="w-slide news-slide">

<!--  JQUERY function work with this parag but not with other loaded from DB  -->

                      <p class="article-text-style">Storea owner Steve Witmere previously arrested for blackmarket bazooka trading. Confesses to involvement in Russian mafia.</p>

                </div>

        </div>

    </body>

        <script >
        $(window).bind("load",function() {
            // Configure/customize these variables.
            var showChar = 100; // How many characters are shown by default
            var ellipsestext = "...";
            var moretext = "Show more >";
            var lesstext = "Show less";


            $('.article-text-style').each(function() {
                var content = $(this).html();

                if(content.length > showChar) {

                    var c = content.substr(0, showChar);
                    var h = content.substr(showChar, content.length - showChar);

                    var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

                    $(this).html(html);
                }

            });

            $(".morelink").click(function(){
                if($(this).hasClass("less")) {
                    $(this).removeClass("less");
                    $(this).html(moretext);
                } else {
                    $(this).addClass("less");
                    $(this).html(lesstext);
                }
                $(this).parent().prev().toggle();
                $(this).prev().toggle();
                return false;
            });
        });
        </script>   

CSS文件:

.morecontent span {
    display: none;
}
.morelink {
    display: block;
}

1 个答案:

答案 0 :(得分:0)

确保您的news_affiche_fiche($newsId);没有在内容周围打印其他标签。鉴于您的javascript,如果内容直接位于<p class="article-text-style">,那么它将起作用,但如果是这样的话,则不会:

    <p class="article-text-style">
        <p class="another-p">text here</p>
    </p>