仅在完整单词后插入 HTML

Insert HTML only after a full word

本文关键字:插入 HTML 单词      更新时间:2023-09-26

我正在使用jquery在锚点之后插入内容。例如,如果我有以下内容:

<p>this is an example sentence with a link coming up (Here's the <a href='#' class='insertpoint'>link content</a>). More text may or may not follow here.</p>

使用以下方法:

$("a.insertpoint").click(function() {  
   var mapDiv = $("<div class='map' id='testmap'><img src='graphics/loading.gif'></div>");
   mapDiv.insertAfter($(this));
});

问题是某些链接后面有括号/大括号,这为新的div 创建了一个丑陋的拆分。有没有一种好的方法可以查看链接后面是否有空格或段落结尾,如果没有,请移动任意字符直到到达空格?

试试这个:

$(this).parent().appendChild(mapDiv);

假设您希望新元素出现在包含链接的元素的末尾,这就是您的示例所示,这应该可以工作

更新:

<p>this is an example sentence with a link coming up (Here's the <span><a href='#' class='insertpoint'>link content</a>)</span>. More text may or may not follow here.</p>

为了使我以前的解决方案起作用,您可以简单地将链接包装在一个范围内,以便锚点父级的末尾是您要插入新元素的位置

或者,如果你想处理查看html,这里有一个解决方案的开始,它将找到定位标签后面的字符,但这个解决方案要求你所有的锚点都有一个唯一的id,并且id是最后一个属性,即它应该出现在结束标签之前:

.HTML:

<p>this is an example sentence with a link coming up (Here's the <a href='#' class='insertpoint' id="1">link content</a>). More text may or may not follow here.</p>

Javascript:

$("a.insertpoint").click(function() {  
    var mapDiv = $("<div class='map' id='testmap'><img src='http://lorempixel.com/400/200/'></div>");
    var parent = $(this).parent();
    var indexOfAnchorId = $(parent).html().indexOf($(this).attr("id"));
    var indexOfAnchorEnd = indexOfAnchorId + $(this).html().length + 7;
    alert($(parent).html()[indexOfAnchorEnd]);
   //mapDiv.insertAfter($(this));
});

小提琴:http://jsfiddle.net/y09cvu6q/

您可以尝试使用.split()

var str = "...a link coming up (here's the link content)."
var words = str.split(" ");
var lastWord = words[words.length - 1];

这应该让你进入正确的领域,开始做任何你想做的事情。

您也许可以执行以下操作:

var link = '<a href="somewhere.com">' + lastWord + '</a>';
var newStr = str.replace(lastWord, link);

这是未经测试的,但这是解决方案的开始