I'm creating a html structure from js.

var e = document;

        // HTML Tree
        $this.append(
            $(e.createElement('div')).addClass('wood-bottom'), 
            $(e.createElement('div')).addClass('jalendar-wood')
                .append(
                    $(e.createElement('div')).addClass('jalendar-pages')
                        .append(
                            $(e.createElement('div')).addClass('pages-bottom'),
                            $(e.createElement('div')).addClass('header'),
                            $(e.createElement('div')).addClass('total-bar'),
                            $(e.createElement('div')).addClass('days')
                )
            )
        );

and there are so many createElement('div') statements.

Is there a better solution for this method? If I define var e = document.createElement('div'), it doesn't work like I want.

有帮助吗?

解决方案

What about a custom function?

var div = function(klass){return $(document.createElement('div')).addClass(klass)};

    // HTML Tree
    $this.append(
        div('wood-bottom'), 
        div('jalendar-wood')
            .append(
                div('jalendar-pages')
                    .append(
                        div('pages-bottom'),
                        div('header'),
                        div('total-bar'),
                        div('days')
            )
        )
    );

其他提示

You could use jQuery clone():

var e = document;
var $d = $(e.createElement('div'));

$this.append(
    $d.clone().addClass('wood-bottom'),
    $d.clone().addClass('jalendar-wood')
        .append(
            $d.clone().addClass('jalendar-pages')
            [...]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top