简体   繁体   中英

jQuery: Paste a var with html content into a tag with .appendTo()

Im trying to paste with html content (the one in the var) and paste it in <fieldset id="previewDataBlock">

Obviously Im doing something wrong:

function createPreviewBlock(){
        var emptyBlock = '<ul class=emptyList id=previewBlock>' +
                '<li id=periodLi></li>' +
                '<li id=companyLi></li>' +
                '<li id=industryTypeLi></li>' +
                '<li id=idustriaDeEmpresaLi></li>' +
                '<li id=jobTypeLi></li>' +
                '<li id=actionsLi></li>' +
                '</ul>';
        emptyBlock.appendTo('fieldset#previewDataBlock');
        $('ul#previewBlock').removeClass('emptyList').css('display', 'block');

}

because I'm getting this error:

TypeError: emptyBlock.appendTo is not a function { message="emptyBlock.appendTo is not a function",  more...}

Currently it's just a string of HTML (but still a string ), you need to make it a jQuery object to use .appendTo() , like this:

 $(emptyBlock).appendTo('fieldset#previewDataBlock');

Or just use .append() , like this:

$('fieldset#previewDataBlock').append(emptyBlock);

As an aside, to be a bit safer use quotes on your attributes, for example:

    var emptyBlock = '<ul class="emptyList" id="previewBlock">' +

by mixing single and double quotes like this you can still keep it pretty clean.

You need to put emptyblock in a jQuery object.

$(emptyblock).appendTo( /* etc*/ );

Here's a bit friendlier version of your code:

function createPreviewBlock(){
    $(['<ul class="emptyList" id="previewBlock">',
        '<li id="periodLi"></li>',
        '<li id="companyLi"></li>',
        '<li id="industryTypeLi"></li>',
        '<li id="idustriaDeEmpresaLi"></li>',
        '<li id="jobTypeLi"></li>',
        '<li id="actionsLi"></li>',
        '</ul>'].join(''))
        .appendTo('#previewDataBlock');
    $('#previewBlock').removeClass('emptyList').css('display', 'block');
}

I use a join instead of concatenation, because IE 6 and 7 suck at garbage collection when concatenating. Also, you can just pass everything right into the jQuery object and avoid the variable. This allows you to use method chaining. Lastly, you'll want to just use ID's in the selectors. It's faster than prepending with an element like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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