我有以下用truncateMe ID创建多个div块,我想截断这个div中的内容。
<ul class="usernews">
@foreach(var news in Model.News){
<li>
<div class="usernews_img">image</div>
<div class="usernews_info">
<div class="truncateMe">@Html.Raw(@news.News.NewsContent)</div>
</div>
</li>
}
</ul>
<script type="text/javascript">
var len = 100;
var p = document.getElementById('truncateMe1');
if (p) {
var trunc = p.innerHTML;
if (trunc.length > len) {
/* Truncate the content of the P, then go back to the end of the
previous word to ensure that we don't truncate in the middle of
a word */
trunc = trunc.substring(0, len);
trunc = trunc.replace(/\w+$/, '');
/* Add an ellipses to the end and make it a link that expands
the paragraph back to its original size */
trunc += '<a href="#" ' +
'onclick="this.parentNode.innerHTML=' +
'unescape(\'' + escape(p.innerHTML) + '\');return false;">' +
'...<\/a>';
p.innerHTML = trunc;
}
}
</script>
然后我有这个java脚本,它适用于具有truncateMe id的单个div。如何使用truncateMe id对每个div应用相同的内容?
答案 0 :(得分:1)
如果你被允许使用jQuery,这真的很容易。
$.fn.truncate = function(options) {
options = $.extend({maxLength:100}, options);
this.each(function() {
var $this = $(this);
var html = $this.html();
if (html.length <= options.maxLength) return;
html = html.substring(0, options.maxLength);
html = html.replace(/\w+$/, '');
html += '<a href="#" ' +
'onclick="this.parentNode.innerHTML=' +
'unescape(\'' + escape($this.html()) + '\');return false;">' +
'...<\/a>';
$this.html(html);
});
}
然后使用它:
$('.truncate-me').truncate(); // use a CSS class instead of IDs