How to use jQuery each() function within append()

2019-02-15 16:34发布

Maybe I'm just missing something simple, but it doesn't seem like anyone else has asked this question anywhere. I'm trying to create a new section of HTML nodes and would like to be able to do it all in a concise and chained manner.

Basically I'd like to do something like this:

var options = {
    buttons: {
        'New':  function() { /* Do some work*/ }
        'Edit': function() { /* Do some work*/ }
        // etc.
    }
};
$( '#container' ).append(
    $( '<div />', { 'class': 'table' } ).append(
        $( '<div />', { 'class': 'row' } ).append( function() {
            $.each(options.buttons, function(key, value) {
                $( '<button />', { text: key } ).click(value);
                // Somehow return this object so the append can work with it
            });
        })
    )
);

What I'd like to have happen is to have it so that the each function is able to return a button element with the click handler associated with it for each button in the options object. There are other options in for which I'd like to do the same thing, but I can't figure out the syntax.

I know this can be done with the reverse having the $.each function contain the .append() function, but this seems to have a performance hit for long collections. Anyone have any suggestions?

Edit: I should note that I have tried the following as a work around, but I have to insert a new unneeded element.

$( '<div />', { 'class': 'row' } ).append( function() {
    var div = $( '<div />', { } );
    $.each(options.buttons, function(key, value) {
        div.append( $( '<button />', { text: key } ).click(value) );
    });
    return div;
})

2条回答
beautiful°
2楼-- · 2019-02-15 16:51

You might want to take a look at jQuery.map().

This takes an array and returns an array. Thus, you can return your array of DOM elements for .append to consume.

查看更多
Juvenile、少年°
3楼-- · 2019-02-15 16:53

Use $.map instead of $.each:

return $.map(options.buttons, function(value, key) {
    return $( '<button />', { text: key } ).click(value)[0]; // return DOM node
});

JSFIDDLE DEMO


Note that you can shorten it a bit if you get rid of the function of one of the appends:

$( '#container' ).append(
    $( '<div />', { 'class': 'table' } ).append(
        $( '<div />', { 'class': 'row' } ).append( 
            $.map(options.buttons, function(value, key) {
                return $( '<button />', { text: key } ).click(value)[0];
            })
        )
    )
);

JSFIDDLE DEMO

查看更多
登录 后发表回答