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

假装没事ソ 提交于 2019-12-01 00:41:56

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

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.

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