插入< br />使用jQuery标记x个单词后 [英] Insert a <br /> tag after x words using jQuery
问题描述
我想在标题中的5个单词后插入< br />
,但我正在使用的那段代码不起作用。请参阅以下内容:
$(#post-id> h2)。each(function(){
var html = $(this).html()。split();
html = html [0] +< br />+ html.slice(1).join( );
$(this).html(html);
});
这个功能很好用 - 如果你想添加< 第一个字后的br />
tage。但是,如果我将其更改为 html.slice(5)
,那么它将无法正常工作。
怎么可能我解决了这个问题,所以5个单词后工作正常吗?或者可能采用不同的方法更合适?感谢您的帮助!
$(#post-id> h2)。each(function(){
var html = $(this).html()。split();
html = html.slice(0,5).join( )+< br />+ html.slice(5).join();
$(this).html(html);
});
基本思路是通过从索引零切片获取前5个单词,并获得数组的5个元素,加入它们,添加你的break标记,然后在索引5中获取数组中的其余元素(作为基于零的索引)并将它们与空格连接并将其转储到最后
编辑
为了获得完整答案,如果OP确实想要在每5个字后拆分,这是另一种方法<每一个(函数(){
var html = $(this).html($) ).split();
var newhtml = [];
for(var i = 0; I< html.length; i ++){
if(i> 0&&(i%5)== 0)
newhtml.push(< br />);
newhtml.push(html [i]);
}
$(this).html(newhtml.join());
});
I am trying to insert a <br />
after 5 words in a title, but the piece of code I'm using doesn't work. Please see below:
$("#post-id > h2").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br />" + html.slice(1).join(" ");
$(this).html(html);
});
This function works well as it is - if you want to add a <br />
tage after the first word. But if I change it to html.slice(5)
then it doesn't work properly.
How could I fix this so it works fine after 5 words? Or maybe a different approach would be more appropriate? Thanks for your help in advance!
$("#post-id > h2").each(function() {
var html = $(this).html().split(" ");
html = html.slice(0,5).join(" ") + "<br />" + html.slice(5).join(" ");
$(this).html(html);
});
Basic idea is you take the first 5 words via slicing from index zero, and getting 5 elements of the array, join them, add your break tag, then get the remaining elements in the array at index 5 (as its a zero based index) and join them with spaces and dump it on the end
edit
for the sake of a full answer and if the OP does want to split after every 5 words, here's another method
$("h2").each(function() {
var html = $(this).html().split(" ");
var newhtml = [];
for(var i=0; i< html.length; i++) {
if(i>0 && (i%5) == 0)
newhtml.push("<br />");
newhtml.push(html[i]);
}
$(this).html(newhtml.join(" "));
});
这篇关于插入< br />使用jQuery标记x个单词后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!