Функциональность Read More не работает должным образом при отрисовке html из базы данных с помощью ejs - PullRequest
2 голосов
/ 13 июля 2020

У меня возникла эта проблема, когда я визуализирую некоторый контент HTML из базы данных, где мне нужно добавить кнопку «Читать дальше», но в случае обычной строки «Читать дальше» работает нормально, но для HTML рендеринг контента из БД выполняется в обратном режиме, например: при нажатии на «Читать дальше» выполняется меньше работы по чтению, а при нажатии на «Меньше чтения» - при чтении больше. Я не могу понять, в чем проблема, или я что-то упустил. Помощь будет принята с благодарностью.

Демонстрация проблемы: https://playcode.io/632632/

Заранее спасибо.

<div class="hero-content">
    <div>
        <span class="more">
            <%-showPost[0].postDescription%> 
        </span>
    </div>
</div>

<% - showPost [0 ] .postDescription%> отображает приведенный ниже html код из базы данных ..

<h2>What is Lorem Ipsum?</h2>
<p><strong>Lorem Ipsum</strong>&nbsp;is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<h2>Why do we use it?</h2>
<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. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humor and the like).</p>
                                           

подробнее стиль и сценарий приведены ниже:

<style>
    .morecontent span {
        display: none;
    }
    .morelink {
        display: block;
    }
</style>
<script>
    $(document).ready(function() {
    
    // Configure/customize these variables.
    var showChar=800;// How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read More";
    var lesstext = "Read Less";


    $('.more').each(function() {
        var content = $(this).html();
        console.log('content=======',content)
        if(content.length > showChar) {
            console.log('====true===')
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
            console.log('====C===',c,'====H===',h)
            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().slideToggle( "slow" );
        $(this).prev().slideToggle( "slow" );
        return false;
    });
});
</script>

1 Ответ

0 голосов
/ 14 июля 2020

измените индекс. html как показано ниже, добавьте класс больше только для тега абзаца.

предварительный просмотр в реальном времени - https://playcode.io/635998/

<div class="hero-content">
    <div>
        <span >
            <h2>What is Lorem Ipsum?</h2>
<p class="more"><strong>Lorem Ipsum</strong>&nbsp;is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<h2>Why do we use it?</h2>
<p class="more">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. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
        </span>
    </div>
</div>
 ******************************************************************
 <h1>WITH NORMAL PARAGRAPH ITS WORKING FIND, FOR EXAMPLE:</h1>
   <span class="more">
            What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
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. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
        </span>
...