jQuery使用"count"而不是“切片" [英] Jquery use "count" instead of "slice"
问题描述
我的代码应该在x个单词之后放置一个横幅.该代码正在运行,但不能正常运行,因为它正在使用slice
进行计数或切片.
我需要使用(count >= 20)
而不是slice(0, 20)
My code is supposed to place a banner after x amount of words. The code is working, but not as it should, as it is using slice
to make the counting or slicing.
I need to use (count >= 20)
instead of slice(0, 20)
这样,将对文本中的单词进行计数,而不是对行数进行计数.
这是满足我需要的代码: https://jsfiddle.net/714Lmgfu/3/
但是,此代码中存在一个循环,该循环可以复制图像(如小提琴中所示),而我无法使return false
正常工作.
This way the words in the text will be counted, instead counting the lines.
This is the code that does what I need: https://jsfiddle.net/714Lmgfu/3/
However, there is a loop in this code, which replicates the image (As show in the Fiddle) and I was not able to make return false
working.
所以我得到了一些帮助,这是最终结果 https://jsfiddle.net/scadp0ar/ ,此代码按应有的方式工作,除了如上所述,它不计算单词数.我应该怎么做才能使它计入单词数?
So I got some help and this was the final result https://jsfiddle.net/scadp0ar/, this code is working the way it should, except that, as stated before, it doesn't count the words. What should I change to make it count the words instead?
例如,更改:
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(0, 20).join(' '), function (m) {
return m + img; });
});
针对:
function check() {
if (count >= 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
count = 0;
}
}
推荐答案
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
// Match a word followed by one or more spaces 20 times
// Insert <img>-tag
// Repeat
return h.replace(/([^\s]+\s+){20}/g, function (m) {
return m + img;
});
});
故障:
/ # Start regex
( # Start capturing group
[^\s]+ # Match everything - but space - 1 or more times
# could also be written as .+? that means:
# match everything 1 or more times, but not gready (meaning that if a space is encountered it will stop matching)
\s+ # Match space 1 or more times
) # End group
{20} # repeat 20 times
/ # End regex
g # global flag - will run the regex multiply times until no more matches are posible
这篇关于jQuery使用"count"而不是“切片"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!