如何用jQuery截斷文本,但保留HTML? 嘗試使用以下代碼,但不幸的是不會返回HTML格式。如何用jQuery截斷文本,但保持HTML格式?
var truncate = function() {
$('p.truncated').text(function(index, oldText) {
if (oldText.length > 20) {
return '...' + oldText.substr(-25);
}
return oldText;
});
}
如果您運行該代碼段,您將看到我正在尋找的內容。
var truncate = function() {
$('p.truncated').text(function(index, oldText) {
if (oldText.length > 20) {
return '...' + oldText.substr(-25);
}
return oldText;
});
}
truncate();
var truncate2 = function() {
$("p.truncated2").each(function() {
//var theContent = $(this).text();
var theContent = $(this).html();
var n = theContent.substr(-25);
$(this).html('...' +n);
});
}
truncate2();
p {
margin: 0 0 30px 0;
display: block;
padding: 5px;
}
streak {
color: green;
}
double {
color: orange;
}
p span {
color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How to make something like this...
<p class="sheet">
<streak>start</streak>
<streak>1</streak>
<streak>2</streak>
<double>3</double>
<double>4</double>
<span>5</span>
<span>6</span>
<streak>7</streak>
<streak>8</streak>
<double>9</double>
<double>10</double>
<streak>end</streak>
</p>
...becomes something like this with jquery?
<p>
...
<span>6</span>
<streak>7</streak>
<streak>8</streak>
<double>9</double>
<double>10</double>
<streak>end</streak>
</p>
<hr />Here is a try with jquery but it return text without html elements.
<p class="truncated">
<streak>start</streak>
<streak>1</streak>
<streak>2</streak>
<double>3</double>
<double>4</double>
<span>5</span>
<span>6</span>
<streak>7</streak>
<streak>8</streak>
<double>9</double>
<double>10</double>
<streak>end</streak>
</p>
The second try
<p class="truncated2">
<streak>start</streak>
<streak>1</streak>
<streak>2</streak>
<double>3</double>
<double>4</double>
<span>5</span>
<span>6</span>
<streak>7</streak>
<streak>8</streak>
<double>9</double>
<double>10</double>
<streak>end</streak>
</p>
How can I keep html elements?
謝謝塞繆爾,如果長度值優越,它就會失敗。例如,如果我將6改爲12. if(html.length> 12); html =「... <」+ html.slice(-12).join('><'); – Paul
您可以隨時進行檢查以查看分割後有多少元素,並避免切分超過該值。答案只是向你展示這個概念。 –
這是真的。謝謝:) – Paul