如何在append()中使用jQuery each()函数 [英] How to use jQuery each() function within append()

查看:303
本文介绍了如何在append()中使用jQuery each()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我只是缺少一些简单的东西,但是似乎没有其他人在任何地方问过这个问题.我正在尝试创建HTML节点的新部分,并希望能够以简洁明了的方式完成所有工作.

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

我想发生的事情是让每个函数都能够为options对象中的每个按钮返回一个按钮元素以及与之关联的单击处理程序.我想在其中执行其他操作,但我无法弄清楚语法.

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.

我知道这可以通过以下方式完成:$ .each函数包含.append()函数,但是对于长集合而言,这似乎会降低性能.有人有建议吗?

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?

我应该注意,我已经尝试过以下方法,但是我必须插入一个新的不需要的元素.

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

推荐答案

使用$.map代替$.each:

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

JSFIDDLE演示

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

JSFIDDLE DEMO

这篇关于如何在append()中使用jQuery each()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆