首页 > 解决方案 > InsertAfter 使用 Javascript 的长 HTML 块

问题描述

我试图在使用 javascript 的 div 元素之后插入一个长的 HTML 块。我已经尝试了几种方法,但似乎都没有奏效。这就是我现在所拥有的。如何在使用 Javascript 的 div 容器之后插入一长段 HTML?

注入 Javascript

<script>
  $(function() {
$( "<p class="" style="white-space:pre-wrap;" id="yui_3_17_2_1_1582132982979_54">Sabine the Queen<br>
<strong data-shrink-original-size="75">A Global Real Estate &amp; Lifestyle Brand<br></strong>
<a href="/properties" target="">Our Properties</a></p>" ).insertAfter( ".sqs-gallery" );
    });
</script>


容器

<div class="sqs-gallery">
This is a slideshow.
</div>

标签: javascripthtml

解决方案


看起来您有未转义的引号,可能会弄乱 HTML 标记。将外引号换成单引号或转义内引号

交换引号:

<script>
  $(function() {
$( '<p class="" style="white-space:pre-wrap;" id="yui_3_17_2_1_1582132982979_54">Sabine the Queen<br>
<strong data-shrink-original-size="75">A Global Real Estate &amp; Lifestyle Brand<br></strong>
<a href="/properties" target="">Our Properties</a></p>' ).insertAfter( ".sqs-gallery" );
    });
</script>

请注意我在 HTML 字符串的开头和结尾处添加的单引号

逃脱:

<script>
  $(function() {
$( "<p class=\"\" style=\"white-space:pre-wrap;\" id=\"yui_3_17_2_1_1582132982979_54\">Sabine the Queen<br>
<strong data-shrink-original-size=\"75\">A Global Real Estate &amp; Lifestyle Brand<br></strong>
<a href=\"/properties\" target=\"\">Our Properties</a></p>" ).insertAfter( ".sqs-gallery" );
    });
</script>

要转义字符串中的双引号,应在其前面加上反斜杠。这告诉浏览器这个引号不是第一个的伙伴并继续前进。如果它未转义,那么它认为字符串比你的意思短很多并且会中断


推荐阅读