2

i want to put a link "Read more" in a div 'guest-message' when the number of characters is more then 300.

In the link are some php variables:

<a href="?data=<?php echo $database; ?>&amp;guest=<?php echo $item[3]; ?>" title="permalink" class="permalink">Read more</a>

The jquery function:

    $(".guest-message").each(function () {
        len=$(this).text().length;
        str= $(this).text().substr(0,300);
        lastIndexOf = str.lastIndexOf(" "); 
        if(len>300) {
            $(this).text(str.substr(0, lastIndexOf) + '...Read more');
        }
    });
}); 

So: how can i put the link in the js on the place where now is '...Read more' ?

john
  • 1,263
  • 5
  • 18
  • You would just construct the link when you need it, and then `$(this).html(newLink)` inside your each. But your question is worded oddly. Are you having difficulty with building the link, or with getting access to the php variables? Because in order to access the php variables in javascript, you have to generate javascript that will have that variables value in them. An example would be something like `var database = '= $database ?>';` – Taplar Oct 18 '19 at 20:53
  • No my problem is building the link – john Oct 18 '19 at 20:56
  • Building the link could be as simple and building out the html with string concatenation or string interpolation with template literals. Once you make the html, you can just set it with `html()` as I showed in my first comment. – Taplar Oct 18 '19 at 21:31
  • You can try assigning the php-linked html snippet to a variable and simply include the variable in the jquery function. Like `var temp_link = ' – Ravindra HV Oct 18 '19 at 23:03

1 Answers1

2

Use the following code.

$(".guest-message").each(function () {
    len=$(this).text().length;
    str= $(this).text().substr(0,300);
    lastIndexOf = str.lastIndexOf(" "); 
    if(len>300) {
        $(this).text(str.substr(0, lastIndexOf));
        $(this).append('... <a href="?data=<?php echo $database; ?>&amp;guest=<?php echo $item[3]; ?>" title="permalink" class="permalink">Read more</a>');
    }
});