after(),其他参数不能按预期工作

问题描述 投票:1回答:3

这是有罪的代码:

var openDiv = '<div class="vc_row-full-width vc_clearfix"></div><div data-vc-full-width="true" data-vc-full-width-init="true" class="vc_row wpb_row vc_row-fluid vc_row-has-fill" style="padding:1em 0 0 0"><div class="wpb_column vc_column_container vc_col-sm-12"><div class="vc_column-inner"><div class="wpb_wrapper"><div class="wpb_text_column wpb_content_element" style="margin-bottom:0"><div class="wpb_wrapper"><div class="sharing"><span>Share this post:</span>';
var social = '<span>FB</span>';
var closeDiv = '</div></div></div></div></div></div></div>';
jQuery(document).ready( function(){
    jQuery(".splash").after(openDiv, social, closeDiv);
});

它很好地显示了开放Div和关闭Div的内容,但社交中的内容在这些div之外显示...我得到正确的结束标记,不明白为什么会发生。

谢谢你的帮助。

jquery arguments
3个回答
1
投票

问题是因为您只能追加元素作为一个整体。 HTML渲染器会自动添加HTML字符串中缺少的结束标记,因此social的内容会显示在您期望的位置之外。

要解决此问题,只需在追加它们之前连接所有字符串:

jQuery(document).ready(function($)  {
  $(".splash").after(openDiv + social + closeDiv);
});

1
投票

当字符串以<开头时,jQuery将其作为DOM节点元素处理。所以代码中的问题是jQuery认为你一次插入3个DOM节点元素。但事实并非如此。您将在3个变量中分别插入一个html代码。

尝试替换此代码:

jQuery(".splash").after(openDiv + social + closeDiv);

1
投票

我觉得你在这里有点意思

jQuery(document).ready( function(){
     jQuery(".splash").after(openDiv+ social+ closeDiv);
});
© www.soinside.com 2019 - 2024. All rights reserved.