jQuery 子字符串截断文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1746115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Substring to truncate text?
提问by n00b0101
I'm trying to figure out how to truncate the first paragraph, and I've tried:
我想弄清楚如何截断第一段,我试过:
$div.children( ('p:eq(0)').substring(0,100));
$div.children( ('p:eq(0)'.substring(0,100)));
But neither have worked...
但两者都没有工作......
Here's the complete code (which someone here helped me with!)
这是完整的代码(这里有人帮助我!)
$j('#hp-featured-item > div[id^="post-"]').each(function() {
var $div = $j(this),
$h2 = $div.find('h2:first'),
$obj = $div.find('object, embed, img').filter(':first'),
id = this.id.match(/^post-([0-9]+)$/);
if( $obj.size() > 0){
// Find parent
var $par = $obj.closest('p');
// Move to top of div
$obj.prependTo($div);
// Remove the now empty parent
$par.remove();
if( $obj.is('img')){
// You can't wrap objects and embeds with links, so make sure we just wrap images
$obj.wrap( $j('<a></a>').attr('href', '/blog/?p='+id[1]));
}
}
// Wrap the contents of the h2, not the h2 itself, with a link
$h2.wrapInner( $j('<a></a>').attr('href', '/blog/?p='+id[1]) );
$div.children( ('p:eq(0)').substring(0,100));
$div.children('p:gt(0)').remove();
});
回答by mauris
This should work:
这应该有效:
$fC = $div.children("p:first-child");
$fC.html($fC.html().substring(0, 100));
Tested: it worked for me. My mock-up code: http://pastebin.com/f737f7ce9
测试:它对我有用。我的模型代码:http: //pastebin.com/f737f7ce9
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div>
<p>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.</p>
<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 humour and the like).</p>
</div>
<div>
<p>Integer ut sapien vitae orci vehicula mattis at eget lacus. Duis enim purus, sagittis nec euismod vitae, laoreet sit amet augue. Sed lacus risus, congue ac cursus et, consectetur at erat. Vestibulum lobortis tincidunt risus, in malesuada lacus ultrices et. Nulla commodo lectus pharetra purus pulvinar auctor. Duis urna felis, consequat ac facilisis id, ultrices ac tellus. Aliquam id semper dolor. Aenean eu augue augue. Vestibulum a elit turpis. Sed sed dignissim augue. Maecenas malesuada aliquet mi, sit amet facilisis quam posuere ut. Nulla luctus nulla vitae est vehicula mattis. Sed in nisi ac urna egestas condimentum. Nulla facilisi. Proin sit amet justo purus. </p>
<p>Vestibulum ut elit neque, eget blandit nulla. Mauris tortor nulla, tincidunt gravida placerat vel, iaculis nec ipsum. Donec sed quam massa, at dignissim arcu. Sed porta mattis elementum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur vel turpis eget urna eleifend egestas sit amet ut nibh. Integer vitae varius neque. Nullam leo libero, condimentum in mollis ut, ornare et nulla. Etiam at quam quis sapien rutrum porttitor. Ut pellentesque mi vitae odio pellentesque sagittis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus a sapien nulla, a ultricies nibh. Curabitur lectus quam, rhoncus quis elementum a, congue auctor sem. </p>
</div>
<script type="text/javascript">//<!--
$(window).ready(function(){
$("div").each(function(){
var $div = $(this);
var $fC = $div.children("p:first-child");
$fC.html($fC.html().substring(0,100));
});
});
// --></script>
</body>
</html>
回答by jpsimons
$div.children( ('p:eq(0)').substring(0,100));
Look at that line. It's taking the first 100 characters of "p:eq(0)" and using that as a selector for the children. The first 100 characters will just be itself, so no trunction. thephpdeveloperis right, you want the innerHTML. Except, if the paragraph has HTML as contents you don't want to split a tag. So use text
instead.
看看那条线。它采用“p:eq(0)”的前 100 个字符并将其用作子项的选择器。前 100 个字符就是它自己,所以没有截断。thephpdeveloper是对的,你想要innerHTML。除了,如果段落包含 HTML 作为内容,您不想拆分标签。所以text
改用。
var truncatedText = $div.children('p').eq(0).text().substring(0, 100);
$div.empty().append(jQuery("<div/>").text(truncatedText));
Also, why do all your variables start with $? That's normally reserved for important system-level variables.
另外,为什么所有变量都以 $ 开头?这通常是为重要的系统级变量保留的。
回答by namretiolnave
Since I'm REALLY grateful for this post and the huge help it is, I am sharing a cool modification I just did.
由于我真的很感谢这篇文章和它的巨大帮助,我分享了我刚刚做的一个很酷的修改。
This code will prevent the append if there are less than 10 chars, and conditionally have a "tool-tip" work too.
如果少于 10 个字符,此代码将阻止追加,并且有条件地也有“工具提示”工作。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">//
$(window).ready(function(){
$("div").each(function(){
$("#div2").hide();
var $div = $(this);
var $fC = $div.children("p:first-child");
//show hide functions in vars
var fn1 = function(){ $('#div2').show();};
var fn2 = function(){ $('#div2').hide();};
$("#div2").hide();
///conditional
if ($fC.text().length > 10)
{
$fC.html($fC.html().substring(0,14));
($fC).append("[...]");
//show hide
($fC).mouseover(fn1).mouseout(fn2);
}
});
});
</script>
</head>
<body>
<div>
<p>first really long line</p>
<p>UNTOUCHED 2nd child</p>
</div>
<div>
<p>1111 </p>
<p>UNTOUCHED 2nd child</p>
</div>
<div id="div2">full text in tooltip content here will probably be
an ajax call or something</div>
</body>
</html>