javascript - Jquery使用 "count"而不是 "slice"

标签 javascript jquery

我的代码应该在 x 个单词后放置一个横幅。该代码可以工作,但没有达到应有的效果,因为它使用 slice 进行计数或切片。 我需要使用 (count >= 20) 而不是 slice(0, 20)

这样就会计算文本中的单词数,而不是计算行数。 这是执行我需要的代码:https://jsfiddle.net/714Lmgfu/3/ 但是,此代码中有一个循环,它复制了图像(如 fiddle 中所示),并且我无法使 return false 工作。

所以我得到了一些帮助,这就是最终结果 https://jsfiddle.net/scadp0ar/ ,此代码按其应有的方式工作,除了如前所述,它不计算单词数。我应该改变什么才能让它计算单词数?

例如,更改:

  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

关于javascript - Jquery使用 "count"而不是 "slice",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556235/

相关文章:

javascript - 我正在编写一个页面,该页面在单击链接时向下滚动。点击后显示为蓝色

javascript - WordPress 插件中的 jQuery

javascript - 如何在 ASP.Net MVC 5 应用程序中的 JQueryUI DatePicker 中设置最小和最大日期

javascript - 如果用户单击表行,则显示或隐藏表行(HTML/JQuery)

javascript - 如何使用 jquery 库限制鼠标移动到 div

asp.net - 使用 OnClientClick 检查 ValidationSummary 是否有效

javascript - 如何访问在 ember 中的路由或组件中设置的模板文件上的变量

javascript - 使用 “each” 元素通过 JQuery 过滤表

javascript - 通过ajax将复杂对象发送到 Controller

javascript - 动态改变href angular JS的路径