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

丶灬走出姿态 提交于 2019-11-30 19:09:06

问题


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;
})

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/8512869/how-to-use-jquery-each-function-within-append

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!