仅在完整单词后插入 HTML
Insert HTML only after a full word
我正在使用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);
这是未经测试的,但这是解决方案的开始
相关文章:
- 使用PHP插入HTML在JavaScript上不起作用
- 如何使用innerHtml正确插入html
- AngularJS指令,在元素后插入HTML
- 使用jQuery插入HTML页面的第一个项目缺少结束标记
- 通过jQuery插入HTML不起作用
- 通过javascript以编程方式将文件插入HTML输入
- 在DIV中动态插入HTML并访问新元素
- 在所有元素中插入HTML
- 在其他图像下使用javascript将图像插入html
- 在工具提示Javascript中插入HTML
- 在HTML字符串的某个段落后插入HTML
- 可以插入在插入HTML标记之前
- 从 AngularJS 将文本插入 HTML
- 将 javascript 返回值插入 html
- 流路由器 - 将内容插入 HTML 模板
- 插入html时是否有触发事件的方法
- JavaScript-插入HTML的内容部分
- jquery多次在元素之间插入html
- 将当前年份插入HTML
- 在光标位置插入HTML,并使用javascript将光标移动到插入的HTML的末尾