简体   繁体   English

jQuery插入动态HTML作为字符串,而不是HTML?

[英]jquery inserting dynamic html as string instead of html?

I have the following code which inserts a div at the top of a page: 我有以下代码在页面顶部插入div:

function setUpAnnouncementsContainer()
{
    var announcements = 'Letterpress scenester franzen, shabby chic meh hella knausgaard 3 wolf moon craft beer ethical chillwave hot chicken beard. Tbh vexillologist tousled .';
    var divAnnouncements = '<div id="divAnnouncements">' + announcements + '</div>';
    var divAnnouncementsContainer = '<div id="divAnnouncementsContainer" class="col-xs-12 col-md-12 col-xl-12">' + divAnnouncements + '</div>';
    var rowAnnouncements = '<div class="row">' + divAnnouncementsContainer + '</div>';

    var isHomePage = $('#hdnIsHomePage').length > 0;
    if (isHomePage)
    {
        //set up divAnnouncementsContainer for homepage
        $('.container')[1].after(rowAnnouncements);
    }
    //else set up divAnnouncementsContainer for other pages
    else $('div.row.breadcrumb-div').after(rowAnnouncements);
}

Notice that my jQuery appends the html differently if the page is the home page vs a page that isn't the home page. 请注意,如果该页面是主页页面而不是非主页页面,那么我的jQuery将以不同的方式附加html。 The code for non-homepage inserts a div as expected but the code for homepage inserts a string representation of the html as opposed to the html itself. 非主页的代码按预期插入div,但主页的代码插入html的字符串表示形式,而不是html本身。

I tried wrapping the dynamic homepage code with a jQuery selector but this displays "[Object][Object]" on the homepage instead of the expected html elements. 我尝试用jQuery选择器包装动态首页代码,但这会在首页上显示“ [Object] [Object]”,而不是预期的html元素。 I also tried wrapping the dynamic homepage code with a jQuery selector and .html() at the end but this just renders the html as a string instead of an element. 我还尝试在动态首页代码的末尾加上jQuery选择器和.html(),但这只是将html呈现为字符串而不是元素。 Any idea what I might be doing wrong here or how to fix? 知道我在这里做错了什么或如何解决?

Well $('.container')[1] does not return a jQuery object but a DOM node. $('.container')[1]不会返回jQuery对象,而是返回DOM节点。

So you are using the native after command which works differently ( and is experimental ). 因此,您正在使用本机的after命令,该命令的工作方式有所不同( 并且是实验性的 )。

Use $('.container').eq(1) instead 使用$('.container').eq(1)代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM