javascript - 仅在完整单词后插入 HTML

标签 javascript jquery html css

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

<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>

为了使我之前的解决方案有效,您可以简单地将链接包装在一个跨度中,以便 anchor 父级的末尾是您想要插入新元素的位置

或者,如果你想处理查看 html,这里是一个解决方案的开始,它将找到 anchor 标签后面的字符,但这个解决方案要求你所有的 anchor 都有一个唯一的 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));
});

fiddle :http://jsfiddle.net/y09cvu6q/

关于javascript - 仅在完整单词后插入 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27911408/

相关文章:

javascript - document.body.style.backgroundColor 不适用于外部 CSS 样式表

html - 圆 Angular 周围的盒子阴影?

JavaScript OPTIONS 对象不会改变

javascript - 如何在现有的 Materialise css 按钮和导航栏中添加自定义 css 样式?

javascript - Google Maps API v3 - infoWindows 均具有相同的内容

Javascript Apexchart x 轴标题始终位于错误位置

javascript - 使用合并单元格在表格上无限滚动(定义的 colspan/rowspan)

php - 用于显示数据的 Mysql 查询

jQuery ajax错误函数即使查询成功也会执行

jquery - Select2 - 未找到匹配项时禁用提交按钮