简体   繁体   English

jQuery使用“计数”而不是“切片”

[英]Jquery use “count” instead of “slice”

My code is supposed to place a banner after x amount of words. 我的代码应该在x个单词之后放置一个横幅。 The code is working, but not as it should, as it is using slice to make the counting or slicing. 该代码正在运行,但不起作用,因为它使用slice来进行计数或切片。 I need to use (count >= 20) instead of slice(0, 20) 我需要使用(count >= 20)而不是slice(0, 20)

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/714Lmgfu/3/但是,此代码中存在一个循环,该循环复制图像(如小提琴中所示),而我无法制作return false工作。

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. 所以我得到了一些帮助,这是最终结果https://jsfiddle.net/scadp0ar/ ,此代码按照应有的方式工作,除了如上所述,它不计算单词数。 What should I change to make it count the words instead? 我应该更改什么以使其计入单词数呢?

For example, change: 例如,更改:

  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; });
            });

for: 对于:

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;
    });
});

Breakdown: 分解:

/ # 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

Try using String.prototype.match() with RegExp /\\w+./g to match alphanumeric character followed by any single character , Array.prototype.splice() 尝试将String.prototype.match()RegExp /\\w+./g一起使用,以匹配字母数字字符,后跟任何单个字符Array.prototype.splice()

 var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' var text = document.querySelector(".newsitem_text"); var html = text.innerHTML, matches = html.match(/\\w+./g); matches.splice(20, 0, img); text.innerHTML = matches.join(" "); 
 <div style="width:450px; margin-left:auto; margin-right:auto" class="newsitem_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pellentesque urna eu pulvinar maximus. Sed elit nunc, vestibulum ut eros vitae, pellentesque rhoncus ipsum. In et metus non diam porttitor maximus iaculis nec lectus. Quisque sodales scelerisque auctor. Nam rutrum venenatis eros, eu condimentum erat placerat ut. Pellentesque sed tempus sem, eu viverra ipsum. Vestibulum nec turpis convallis, dapibus massa vitae, posuere mauris. Suspendisse mattis tincidunt lorem. Aliquam erat volutpat. Nullam at tincidunt erat, maximus laoreet ipsum. Quisque nunc neque, semper tincidunt placerat eget, blandit a ante. Suspendisse pulvinar, velit eu ultrices pulvinar, lacus sapien tincidunt ipsum, eget sollicitudin mauris eros molestie ex. Etiam quis orci dui. Phasellus vestibulum mollis molestie. Nam condimentum ornare nisl, sed finibus risus tempus vel. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum eget ullamcorper lorem. Aliquam mollis elit in sem dapibus dapibus. Proin vel massa a arcu dictum tincidunt in ut ante. Sed feugiat tempus dictum. Praesent in leo ullamcorper, sodales turpis et, vehicula tellus. Duis pellentesque dui ac turpis tristique imperdiet. Sed sed orci lectus. Suspendisse non egestas sem, sed tincidunt sem. Etiam laoreet dui sem. Mauris hendrerit massa tempus, euismod arcu sit amet, eleifend quam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus id fringilla mauris. Cras dapibus non lacus at finibus. Nullam vitae sagittis neque. Mauris libero velit, interdum non vehicula non, lacinia non augue. Maecenas elementum lacinia interdum. Morbi eget mollis nisl. Integer accumsan condimentum tellus, lacinia pellentesque urna volutpat a. Nullam semper sem et erat commodo sollicitudin. Proin rhoncus felis eu aliquam venenatis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla pretium velit eu molestie condimentum. Vestibulum vitae velit mi. Integer nec leo quam. Nam pulvinar ligula congue consectetur tristique. Donec placerat faucibus diam sit amet fermentum. Ut id pellentesque risus. Nunc lacus orci, rhoncus ut risus sed, mattis posuere tellus. Nulla pellentesque eros sed neque consectetur dictum.</div> 

jsfiddle https://jsfiddle.net/scadp0ar/3/ jsfiddle https://jsfiddle.net/scadp0ar/3/

You should try something like this: 您应该尝试这样的事情:

 var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />';

 jQuery( document ).ready(function( $ ) {
     $(".newsitem_text").html(getTextWithImageBetweenWords($(".newsitem_text").html(),20));
 });

 function getTextWithImageBetweenWords(text, count){
   var split_text = text.split(' ');
   var _out = []; 
   var words = split_text.length;
   for(var i=0;i < words; i++){
       if(i !== 0 && i === count){          
        _out[i] = split_text[i] + img;
       }
       else{
           _out[i] = split_text[i];
       }      
   }

   return _out.join(' ');
 }

This is a more readable and easy way to accomplish this, here is the JSFiddle! 这是一种更易读,更轻松的方法, 这是JSFiddle!

Note: if you want to repeat the image every n (20 in your case) words, just change i === count for i % count === 0 . 注意:如果要每n个单词(在您的情况下为20个)重复图像,只需将i === count更改为i % count === 0

From your comment, you may want to edit the question (just for clarity not trying to be a jerk). 从您的评论中,您可能想要编辑问题(为清楚起见,不要试图成为一个混蛋)。 Also, by splitting at space, the count is of words. 另外,通过在空间上分割,计数为单词数。 '\\s' is space '\\n' is new line '\\t' is carriage return, '\\r\\n' is a special type of carriage return. '\\ s'是空格'\\ n'是换行'\\ t'是回车符,'\\ r \\ n'是回车符的一种特殊类型。 You could potentially make a more complicated regex to cover everything that is not a new line or a space '\\t|\\s|\\r\\n'. 您可能会制作更复杂的正则表达式,以涵盖不是换行符或空格'\\ t | \\ s | \\ r \\ n'的所有内容。 To place the image within lines, you can use a styling trick as explained later. 要将图像放置在线条中,可以使用样式技巧,如稍后所述。

If you want to have the image not repeat change: 如果您不想重复图像,请更改:

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;
    }
  }

For an even nicer fit, try align="right" which will wrap the text around the image. 为了获得更好的拟合效果,请尝试align =“ right”,它将文本环绕在图像周围。

//jQuery(function ($) {

jQuery( document ).ready(function( $ ) {


    var img = '<img align="right" 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(20,21).join(' '), function (m) {
            return m + img; });
            });
});

to

function check() {
    if (count == 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />';
    }
  }

To avoid using a nasty loop, you could slice at a different location or use splice: 为避免使用讨厌的循环,可以在其他位置切片或使用拼接:

//jQuery(function ($) {

jQuery( document ).ready(function( $ ) {


    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(20, 21).join(' '), function (m) {
            return m + img; });
            });
});

To wrap your image within the words use align="left" or align="right" in the image tag. 要将图像包装在单词中,请在image标签中使用align =“ left”或align =“ right”。

<img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM