jQuery-使用split仅拆分文本? [英] jquery - Use split to split only text?

查看:84
本文介绍了jQuery-使用split仅拆分文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码拆分文本,并在一定数量的单词之后放置一个html代码.它正在工作,问题在于split函数不仅可以拆分文本,还可以拆分HTML.如何将其配置为仅拆分文本?假设我有一篇文章,并且需要在文章的中间显示横幅,如果我不小心,我会拆分一些div或类似的东西.

My code splits the text and place a html code after a certain number of words. It's working, the problem is that the split function not only splits text, but also splits HTML. How can I configure it to split text only? Let's say I have an article and I need a banner to appear in the middle of the article, if I don't take care, I'll split some div or something like that.

代码如下:

<script type="text/javascript">
 jQuery(function($) {


var wordList = $(".newsitem_text").html().split(' ');
var newHtml = '';

$.each(wordList, function(index, word){
  newHtml += ' ' + word;
  if (index == 10) {
    newHtml += 'Some HTML goes here'     
  }        
})
;

$(".newsitem_text").html(newHtml);

});

</script>

推荐答案

您应该使用jQuery的.contents()方法,并且在逐字复制其他所有内容时仅拆分文本标签.像这样:

You should use jQuery's .contents() method and split only text tags while copying everything else verbatim. Something like this:

jQuery(function($) {

  var newHtml = '';
  var count = 0;

  function check() {
    if (count >= 20) {
      newHtml += 'Some HTML goes here'     
      count = 0;
    }
  }

  $(".newsitem_text").contents().each(function () {

    if (this.nodeType != 3) {
      newHtml += this.outerHTML;
      count += $(this).text().trim().split(/\s+/).length;
    }
    else {
      var wordList = $(this).text().trim().split(/\s+/);

      $.each(wordList, function(index, word){
        count++;
        check();
        newHtml += ' ' + word;
      })
    }

  });

  check();

  $(".newsitem_text").html(newHtml);

});

这篇关于jQuery-使用split仅拆分文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆