Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.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 如何在div文本的某个位置插入html对象?_Javascript_Jquery - Fatal编程技术网

Javascript 如何在div文本的某个位置插入html对象?

Javascript 如何在div文本的某个位置插入html对象?,javascript,jquery,Javascript,Jquery,我有一个div,其中包含一些用户输入文本 我希望能够插入一个html对象,比如说在这个div文本的某个位置 例如: <div> There is some text in this div and I would like to append an html object right here. There might be some other text here. </div> 把它变成: <div> There is some

我有一个div,其中包含一些用户输入文本

我希望能够插入一个html对象,比如说在这个div文本的某个位置

例如:

<div>
    There is some text in this div and I would like to append an html object right here.
    There might be some other text here.
</div>
把它变成:

<div>
    There is some text in this div and I would like to append an html object <span class="safeHtml"></span> right here.
    There might be some other text here.
</div>
需要考虑的一些事情:

我不想将整个div呈现为安全的html,因为用户输入可能包含html标记,这可能会破坏我的设计或一些讨厌的脚本。 我只想将插入的对象呈现为html;其余部分为文本。 谢谢


附言:现在已经足够具体了,还是我应该在黑板上为那些结束提问和投票的人画一幅画?

你可以这样做,在这里替换:

如果只想插入,可以执行以下操作:

$('div').each(function(){
  var html = $(this).html();
  var i = html.indexOf('right here');
  if (i>=0) $(this).html(html.slice(0, i)+'<span>something</span>'+html.slice(i));
});

我很难理解这个问题。但我想,这就是你要找的。

HTML


你可以用一个简单的字符串替换来完成。你应该修改divi编辑的我的问题的innerHTML,请参见上文。。为什么会投反对票?我更新了我的问题,请参见上面的PLST。这仍然会将div内容呈现为安全的html
$('div').each(function(){
  var html = $(this).html();
  var i = html.indexOf('right here');
  if (i>=0) $(this).html(html.slice(0, i)+'<span>something</span>'+html.slice(i));
});
<div>
    Some text. <span id="newText"> </span> .Some more text.
</div>
var htmlObject = "Text from HTML object"; 
$("#newText").append(htmlObject);