Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在html内容之间插入标记_Javascript_Jquery_Html - Fatal编程技术网

Javascript 在html内容之间插入标记

Javascript 在html内容之间插入标记,javascript,jquery,html,Javascript,Jquery,Html,我在mydiv <div id="mydiv"> sample text sample text sample text... ...... <i>inner text </i> <i>sample text </i> ...... <b>sample text </b> <i>sample text </i> </div> 示例文本示例文本示

我在
mydiv

<div id="mydiv">
   sample text sample text sample text...
   ......
   <i>inner text </i> <i>sample text </i>
   ......
   <b>sample text </b> <i>sample text </i>
</div>

示例文本示例文本示例文本。。。
......
内部文本示例文本
......
示例文本示例文本
现在,我想在mydiv内容之间添加高亮显示div。示例如下所示

<div class="highlight">highlight text</div>
突出显示文本
我想每200个单词插入一个div,但问题是它不应该进入任何children标记中。例如,如果第200个单词是内部的,它不应该像

<div id="mydiv">
   sample text sample text sample text...
   ......
   <i>inner<div class="highlight">highlight text</div> text </i> <i>sample text </i>
   ......
   <b>sample text </b> <i>sample text </i>
</div>

示例文本示例文本示例文本。。。
......
innerhighlight文本示例文本
......
示例文本示例文本
它应该附加在内部标记之后

<div id="mydiv">
   sample text sample text sample text...
   ......
   <i>inner text </i> <div class="highlight">highlight text</div> <i>sample text </i>
   ......
   <b>sample text </b> <i>sample text </i>
</div>

示例文本示例文本示例文本。。。
......
内部文本高亮显示文本示例文本
......
示例文本示例文本
我尝试使用子字符串,但它进入了子标记中。有没有办法做到这一点?我们可以使用任何js库。

i标记是一个内联元素,不能在其中插入块元素,如div。并且“highlight”不是div的有效属性

要实现插入,请使用span而不是div。并检查目标需要哪些属性。结果将是(id作为属性):


示例文本示例文本示例文本。。。
......
innerhighlight文本示例文本
......
示例文本示例文本

我想你已经找到了单词200,并在后面加上了div,可能是这样的吧

varUntilSpace200 + '<div "highlight">highlight text</div>' + restOfInnerHTML;
varUntilSpace200+“突出显示文本”+restofinerhtml;
然后,如果在空间200之后有一个

"</"
“”
var indof1=restofinerhtml.indexOf(“已更新
我将在每两个单词后添加的div

var some_div = '<div style="display:inline-block;color:red;">some_text</div>';

var text = $('#mydiv').text().match(/\w+/g);
最后,循环遍历所有唯一的标记,并用html替换它们

要查找令牌,请使用jquery的
$('#mydiv').find(':contains('+j+'$$));

for (var j = 1; j < i; j++) {
  var elm = $('#mydiv').find(':contains(' + j + '$$)');
  if (elm.length == 0) {
    console.log('inroot>>' + ':contains(' + j + '$$)');
    var offset = $(':contains(' + j + '$$)').last().html().indexOf(j + '$$');
    var t_html = $(':contains(' + j + '$$)').last().html().slice(0, (offset + (("" + j + '$$').length))).replace(/[0-9]\$\$/ig, '');
    t_html += some_div;
    t_html += $(':contains(' + j + '$$)').last().html().slice(offset + (("" + j + '$$').length));
    $('#mydiv').html(t_html);

  } else {
    console.log('not inroot>>' + ':contains(' + j + '$$)');
    $(some_div).insertAfter(elm.last());
  }
}
。突出显示{
颜色:红色;
显示:内联块;
}
b{
背景颜色:蓝色;
}
我{
背景颜色:黄色;
}
我
b{
边框:1px纯绿色;
}

示例文本
示例文本示例文本
......
内部文本示例文本
......
示例文本示例文本

您没有给出如何在DOM中获得文本的详细信息(我假设您正在使用DOM)。但是,如果文本节点包含感兴趣的单词,类似的操作应该可以。为了方便起见,我使用了少量jQuery,这几乎没有必要

// use jQuery to find the text node "inner text" from your example
let textNode = $("#mydiv i")
    .first()
    .contents()
    .filter(function () {
        return this.nodeType == 3; /* text node */
    }).get(0);

// find the parent element of the text node
let el = textNode;
while (el.parentNode) {
    if (el.nodeType == 1) break; /* element */
    el = el.parentNode;
}
// append the html after the parent of the text node.
 $(el).after(`<div class="highlight">highlight text</div>`);
//使用jQuery从示例中查找文本节点“内部文本”
设textNode=$(“#mydiv i”)
.first()
.contents()
.filter(函数(){
返回this.nodeType==3;/*文本节点*/
}).get(0);
//查找文本节点的父元素
设el=textNode;
while(el.parentNode){
if(el.nodeType==1)break;/*元素*/
el=el.parentNode;
}
//将html追加到文本节点的父节点之后。
$(el).after(`highlight text`);
你可以在这里看到这一点

基本上,代码获取感兴趣的第n个单词的文本节点,找到它的父元素,然后插入所需的html作为父元素的第一个右同级。

您可以使用JQuery或在目标之后插入元素。

方法将指定的内容作为jQuery集合中每个元素的最后一个子元素插入

$(函数(){
//你找到位置的逻辑在这里。。。
//在元素后追加文本
$(“#mydiv i:第一个孩子”)。之后(“突出显示文本”);
});
。突出显示{
颜色:红色;
}

样本1文本样本1文本样本1文本样本1文本样本1文本样本1文本样本1文本样本2文本样本2文本样本2文本样本2文本样本2文本样本3文本样本3文本样本3文本样本3文本样本3文本样本3文本样本
3文本3样本3文本样本3文本样本3文本样本4样本4文本样本4文本
1内部文本1示例文本1
2内部文本2示例文本2
3内部文本3示例文本3
4内部文本4示例文本4
5内部文本5示例文本5
6内部文本6示例文本6
7内部文本7示例文本7
8示例文本8示例文本8
9示例文本9示例文本9
10示例文本10示例文本10
11示例文本11示例文本11
12示例文本12示例文本12

无论如何,我希望这能有所帮助。

注意:使用的HTML是给定的示例内容
尝试拆分您的div内容并从中进行操作。有关解释,请参阅注释:

        //1.Get mydiv content
        //2. Split spaces and newlines
        //3. Remove empty array values
        var div =     $("#mydiv").html().toString().split(/[\s+\n]/).filter(String);

        var allowAdd = true, appendNow;
        for(var a=0; a < div.length ; a++){
            if(div[a].match(/^</) && div[a].match(/>$/)){ //search for end tags ie. </i>, </b>
                if(div[a].match(/<\//)){ //if end tag, 
                    allowAdd = true;    //allow append
                }
            }else if (div[a].match(/</)){ //if start stag,
                allowAdd = false;   //disallow append (inside block)

            }

            if((a+1)%200 == 0){
                //every 200 words
                appendNow = true;
            }

            //append if 200th word and end tag is passed
            if(appendNow && allowAdd){
                div[a] += ' <div class="highlight">highlight text </div> ';
                appendNow = false;
            }
        }

        //join array values and assign value to mydiv content
        $("#mydiv").html(div.join(" ")); 
//1.Get mydiv内容
//2.拆分空格和换行符
//3.删除空数组值
var div=$(“#mydiv”).html().toString().split(/[\s+\n]/).filter(字符串);
var allowAdd=true,现在追加;
对于(变量a=0;aif(div[a])匹配(/这里有一个代码,它将为您提供所需的结果。此代码的优点是,它不会通过检查每个元素是否包含
来检查每个元素是否是标记。如果您可以将
#mydiv
的HTML作为字符串进行操作,一个解决方案是使用
字符串。将
替换为常规字符串表达式和替换函数,例如:

函数insertinhtmleverywords(n,htmlString,insertString){
var wordCounter=0,
标记深度=0;
返回htmlString.replace(
/]+)>|[^=n){
//如果不在标签内,且单词至少为n,
字计数器=0;
返回match+insertString;
}否则{
复赛;
}
});
}
下面的代码片段包含该方法的工作演示,简化为每2个单词插入一次(如果不在任何标记中,或者直接在下一个可能的结束标记后面插入一个
for (var j = 1; j < i; j++) {
  var elm = $('#mydiv').find(':contains(' + j + '$$)');
  if (elm.length == 0) {
    console.log('inroot>>' + ':contains(' + j + '$$)');
    var offset = $(':contains(' + j + '$$)').last().html().indexOf(j + '$$');
    var t_html = $(':contains(' + j + '$$)').last().html().slice(0, (offset + (("" + j + '$$').length))).replace(/[0-9]\$\$/ig, '');
    t_html += some_div;
    t_html += $(':contains(' + j + '$$)').last().html().slice(offset + (("" + j + '$$').length));
    $('#mydiv').html(t_html);

  } else {
    console.log('not inroot>>' + ':contains(' + j + '$$)');
    $(some_div).insertAfter(elm.last());
  }
}
// use jQuery to find the text node "inner text" from your example
let textNode = $("#mydiv i")
    .first()
    .contents()
    .filter(function () {
        return this.nodeType == 3; /* text node */
    }).get(0);

// find the parent element of the text node
let el = textNode;
while (el.parentNode) {
    if (el.nodeType == 1) break; /* element */
    el = el.parentNode;
}
// append the html after the parent of the text node.
 $(el).after(`<div class="highlight">highlight text</div>`);
        //1.Get mydiv content
        //2. Split spaces and newlines
        //3. Remove empty array values
        var div =     $("#mydiv").html().toString().split(/[\s+\n]/).filter(String);

        var allowAdd = true, appendNow;
        for(var a=0; a < div.length ; a++){
            if(div[a].match(/^</) && div[a].match(/>$/)){ //search for end tags ie. </i>, </b>
                if(div[a].match(/<\//)){ //if end tag, 
                    allowAdd = true;    //allow append
                }
            }else if (div[a].match(/</)){ //if start stag,
                allowAdd = false;   //disallow append (inside block)

            }

            if((a+1)%200 == 0){
                //every 200 words
                appendNow = true;
            }

            //append if 200th word and end tag is passed
            if(appendNow && allowAdd){
                div[a] += ' <div class="highlight">highlight text </div> ';
                appendNow = false;
            }
        }

        //join array values and assign value to mydiv content
        $("#mydiv").html(div.join(" ")); 
var elements = $("#mydiv").contents(); //Get all contents of #mydiv
$("#mydiv").html(null); //Delete all elements from #mydiv

var count = 0; //This will be counting our elements

for(var i = 0; i < elements.length; i++){ //Go through all elements of #mydiv
    if(elements[i].nodeName == "#text"){ //If the element is a text block, then:

        var textElements = $(elements[i]).text().split(/\s+/g); //Split the text by all the spaces

        for(var j = 0; j < textElements.length; j++){ //Go through all elements inside the text block

            if(textElements[j] == "") continue; //The splitting of the text-block elements is not perfect, so we have to skip some elements manually

            count++; //Add to our count

            $("#mydiv").append(textElements[j] + " "); //Add this element to our cleared #mydiv

            if(count != 0 && count % 200 == 0){ //Every 200 elements, do this:
                $("#mydiv").append(" <span class='highlight'>highlight</span> "); //Add our highlight
            }
        }
    }else{ //If the element is not a text block, then:

        $("#mydiv").append(elements[i]); //Add the non-text element

        count++; //Add to our counter

        if(count != 0 && count % 200 == 0){ //Every 200 elements, do this:
            $("#mydiv").append(" <span class='highlight'>highlight</span> "); //Add our highlight

        }
    }
}
$(document).ready(function () {
    // count of characters (modulo the period) and selected period
    var count = 0, period = 200;

    // iterator and highlight
    var words = '', highlight = '<div class="highlight">highlight text</div>';

    // loop through the contents
    $('#mydiv').contents().each(function () {
        // we only care about text contents
        if (this.nodeType === 3) {
            // get the individual words
            words = $(this).text().split(' ');
            // loop through them
            for (var j = 0; j < words.length; j++) {
                // increase count except if the word is empty (mutiple spaces)
                if (words[j] && words[j] !== '\n') { count++; }
                // if the period is exceeded, add the highlight and reset the count
                if (count === period) {
                    words.splice(1 + j++, 0, highlight);
                    count = 0;
                }
            }
            // replace the text
            $(this).replaceWith(words.join(' '));
        }
    });
});