开发者

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><开发者_StackOverflow社区;/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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜