2016-05-05 3 views
0

У меня есть таблица, в которой есть столбцы, которые могут расти на основе содержимого в них, но я хотел бы ограничить этот рост, добавив ссылку «Подробнее» после двух строк строки для конкретный столбец. Так позволяет сказать, что я есть тд, как указано ниже:Добавить кнопку Подробнее ... html

<table> 
    <tr> 
     <td role="gridcell" style="padding-bottom: 50px;"> 
      <p><span style="font-family:'Open Sans', Arial, sans-serif;font-size:14px;line-height:20px;text-align:justify;background-color:#ffffff;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada luctus porta. Sed eu magna quis sem bibendum tincidunt. Pellentesque rhoncus efficitur risus, eu pretium metus consequat quis. Phasellus eget porta augue. Fusce porta magna nisi, vel euismod ante ultrices in. Vestibulum faucibus, lectus sit amet ornare efficitur, est tellus egestas sem, nec consequat tellus lorem eget elit. Morbi venenatis convallis lorem, eu ornare eros blandit posuere.</span> 
      </p> 
      <p><span style="font-family:'Open Sans', Arial, sans-serif;font-size:14px;line-height:20px;text-align:justify;background-color:#ffffff;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada luctus porta. Sed eu magna quis sem bibendum tincidunt. Pellentesque rhoncus efficitur risus, eu pretium metus consequat quis. Phasellus eget porta augue. Fusce porta magna nisi, vel euismod ante ultrices in. Vestibulum faucibus, lectus sit amet ornare efficitur, est tellus egestas sem, nec consequat tellus lorem eget elit. Morbi venenatis convallis lorem, eu ornare eros blandit posuere.</span> 
      </p> 
     </td> 
    </tr> 
</table> 

Я хотел бы, чтобы обернуть как абзацы и показывать только две строки из приведенного выше тд и добавить кнопку «Подробнее», так что при нажатии, что он показывает оставшееся содержимое. Какие-либо предложения?

Код:

listItems.each(function(i, listItems) { 
     var max_length = 150; // set the max content length before a read more link will be added 

     // check for content length 
     if ($(this).html().length > max_length) { 
      // split the content in two parts 
      var short_content = $(this).html().substr(0, max_length); 
      var long_content = $(this).html().substr(max_length); 

      // Alter the html to allow the read more functionality 
      $(this).html(short_content + 
       '<a href="#" class="read_more"><br/>Read More</a>' + 
       '<span class="more_text" style="display:none;">' + long_content + '</span>'); 

      $(this).find('a.read_more').click(function(event) { // find the a.read_more element within the new html and bind the following code to it 
       event.preventDefault(); // prevent the a from changing the url 
       $(this).hide(); // hide the read more button 
       $(this).parents().find('.more_text').show(); // show the .more_text span 
      }); 
     } 
    } 
+0

Взгляните на этот плагин jquery - [Readmore.js] (http://jedfoster.com/Readmore.js/). Это, по крайней мере, хорошее стартовое место, если вы хотите написать свое собственное. –

+0

Поддерживает ли этот jQuery плагин элементы? Как он сохранит абзацы, пролеты, элементы изображения, ссылки и т. Д.? – Neophile

ответ

0

Здесь действительно простое решение, которое принимает только текст из клетки-мишени, разделить его на словах, чем заменить исходный HTML клеток с первыми 10 слов, не добавлял ссылка, которая нажмите обработчик будет добавлять остальную часть исходного текста:

$(function() { 
 
\t // Get the cell 
 
\t var td = $("td.more"); 
 
    
 
    // Get the text and split it into words 
 
    var words = td.text().trim().split(" ").filter(function(w) { 
 
    \t return (w.length > 0) && (w != "\n"); 
 
    }); 
 
    
 
    // Get the basic text first 10 words 
 
    var base = words.slice(0, 10) 
 
    
 
    // Get the rest 
 
    var rest = words.slice(10); 
 
    
 
    // Replace cell original text with first 10 words 
 
    td.html(base.join(" ")); 
 
    
 
    // Append more link to the cell 
 
    $("<a>", { 
 
    \t html: " more..." 
 
    }).css("color", "blue").appendTo(td).click(function() { 
 
    // Remove the link 
 
    \t $(this).remove(); 
 
    
 
    // Append the rest of the original text 
 
    td.append(" " + rest.join(" ")); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td class="more" role="gridcell" style="padding-bottom: 50px;"> 
 
     <p> 
 
     <span> 
 
     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada luctus porta. Sed eu magna quis sem bibendum tincidunt. Pellentesque rhoncus efficitur risus, eu pretium metus consequat quis. Phasellus eget porta augue. Fusce porta magna nisi, vel euismod ante ultrices in. Vestibulum faucibus, lectus sit amet ornare efficitur, est tellus egestas sem, nec consequat tellus lorem eget elit. Morbi venenatis convallis lorem, eu ornare eros blandit posuere. 
 
     </span> 
 
     </p> 
 
     <p> 
 
     <span> 
 
     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada luctus porta. Sed eu magna quis sem bibendum tincidunt. Pellentesque rhoncus efficitur risus, eu pretium metus consequat quis. Phasellus eget porta augue. Fusce porta magna nisi, vel euismod ante ultrices in. Vestibulum faucibus, lectus sit amet ornare efficitur, est tellus egestas sem, nec consequat tellus lorem eget elit. Morbi venenatis convallis lorem, eu ornare eros blandit posuere. 
 
     </span> 
 
     </p> 
 
    </td> 
 
    </tr> 
 
</table>

+0

Спасибо за код. Будет ли приведенный выше код работать для любого элемента html, доступного в столбце? Это могут быть элементы ссылок или промежутки или абзацы. – Neophile

+0

Он использует функцию jQuery 'text()', поэтому он будет работать в пределах этой функции. – xxxmatko

+0

Это хороший ответ! Благодарю. – Neophile

Смежные вопросы