如何创建动态对象?

时间:2014-07-30 11:41:34

标签: javascript jquery

我想使用jquery创建动态对象..

我知道我可以使用这种方法

$('#container').append('<div class="relation"><input type="text" name="relation"></div>');

但是这样,html字符串的实现时间很长。

我有这个HTML

<div class="box-content">
<fieldset>
    <legend><h6>Select Conditions</h6></legend>
        <div class="control-group" id="relation_container">
        <div class="relation-parent_0">
            <div class="relation-left" id="relation_0">
            <select name="key[]" id="key_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <select name="condition[]" id="condition_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <input type="text" name="constraint[]" id="constraint_0" class="relation-input" data-provide="typeahead" data-items="2" style="" />
            </div>
            <div class="relation-reight">
            <button type="reset" class="btn">X</button>
            </div>
        </div>
        </div>                            

</fieldset>
<button type="button" class="btn btn-primary" onclick="add_relation();">Add More</button>
</div>

现在我希望动态生成此部分

<div class="relation-parent_0">
            <div class="relation-left" id="relation_0">
            <select name="key[]" id="key_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <select name="condition[]" id="condition_0" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <input type="text" name="constraint[]" id="constraint_0" class="relation-input" data-provide="typeahead" data-items="2" style="" />
            </div>
            <div class="relation-reight">
            <button type="reset" class="btn">X</button>
            </div>
        </div>

编辑:

我修改了bart s的答案

并像这样重写脚本,

但似乎有一些错误

var i = 0;
    function add_relation()
    {
        i = i + 1;

        var memtag = $('<div />', {
                                    'class' : 'relation-parent_' + i,
                                     html    : $('<div />', {
                                                               'class' : 'relation-left',
                                                               'id'    : 'relation_' + i,
                                                                html    : $('<select />', 
                                                                              {
                                                                             'class'  : 'relation-select',
                                                                             'id'     : 'key_' + i,
                                                                             'name'   : 'key[]'
                                                                              })
                                                            }
                                                ),
                                                $('<div />', {
                                                               'class' : 'relation-right',
                                                                html    : $('<button />', 
                                                                              {
                                                                             'class'  : 'btn',
                                                                             'name'   : 'btn[]'
                                                                              })
                                                            }
                                                )
                                    });

        $("#relation_container").append(memtag);
    }

最终我得到了答案

var i = 0;
    function add_relation()
    {
        i = i + 1;
        var left = $('<div />', {'class' : 'relation-left','id'    : 'relation_' + i}).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                             })).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'condition_' + i,
                                 'name'   : 'key[]'
                             })).append($('<input />', {
                                 'class'  : 'relation-input',
                                 'id'     : 'constraint_' + i,
                                 'type' : 'text',
                                 'name'   : 'constraint[]',
                                 'data-provide' : 'typeahead',
                                 'data-items' : '2'

                             }));
        var right = $('<div />', {'class' : 'relation-right',html : $('<buton />', 
                                                                            {
                                                                            'class' : 'btn',
                                                                            'name' : 'btn[]',
                                                                            'value': 'X'})
                                                                    });


        var parent = $('<div />', {'class' : 'relation-parent_' + i}).append(left).append(right);
    $("#relation_container").append(parent);
    }

这是最终的脚本:

<style>
    .relation-left
    {
        float:left; 
        width: 80%;
    }
    .relation-right
    {
        float:left; 
        margin: 0 0 0 30px;
    }
    .relation-select
    {
       width: 120px !important;
       float:left;
       margin: 0 0 0 2px
    }
    .relation-input
    {
       width: 120px !important;
       margin: 0 0 0 12px
       float:left;
    }
    </style>

    <script type="text/javascript">
    function condition_toggle(condition)
    {
        if(condition==1)
            $("#condition_div").fadeOut('slow');
        else
            $("#condition_div").fadeIn('slow');
    }

    var i = 0;
    function add_relation()
    {
        i = i + 1;
        var left = $('<div />', {'class' : 'relation-left','id'    : 'relation_' + i}).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                             })).append($('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'condition_' + i,
                                 'name'   : 'key[]'
                             })).append($('<input />', {
                                 'class'  : 'relation-input',
                                 'id'     : 'constraint_' + i,
                                 'type' : 'text',
                                 'name'   : 'constraint[]',
                                 'data-provide' : 'typeahead',
                                 'data-items' : '2'

                             }));
        var right = $('<div />', {'class' : 'relation-right',html : $('<buton />', 
                                                                            {
                                                                            'class' : 'btn',
                                                                            'name' : 'btn[]',
                                                                            'value': 'X'})
                                                                    });


        var parent = $('<div />', {'class' : 'relation-parent_' + i}).append(left).append(right);
    $("#relation_container").append(parent);
    }
    </script>   
            <div class="row-fluid sortable">
                <div class="box span12">
                    <div class="box-header well" data-original-title>
                        <h2><i class="icon-edit"></i> Add collection</h2>
                        <div class="box-icon">
                            <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a>
                            <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a>
                            <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a>
                        </div>
                    </div>
                    <div class="box-content">
                        <form class="form-horizontal" action="<?php echo base_url() ?>admin.php/collection/add_collection" method="post" enctype="multipart/form-data">
                          <fieldset>
                            <legend><?php if(isset($msg)) echo $msg;?></legend>
                            <div class="control-group">
                              <label class="control-label" for="typeahead">collection Name</label>
                              <div class="controls">
                                <input type="text" name="title" class="span6 typeahead" id="title"  data-provide="typeahead" data-items="4" >
                              </div>
                            </div>
                            <div class="control-group">
                              <label class="control-label" for="fileInput">File input</label>
                              <div class="controls">
                                <input class="input-file uniform_on" name="img" id="img" type="file">
                              </div>
                            </div>          
                            <!--<div class="control-group" >
                              <label class="control-label" for="textarea2">Description</label>
                              <div class="controls" style="overflow-x: auto;">
                                <textarea class="cleditor" name="cont" id="cont" rows="3"></textarea>
                              </div>
                            </div>-->
                            <div class="control-group">
                                <label class="control-label">Conditions</label>
                                <div class="controls">
                                  <label class="radio">
                                    <input type="radio" name="gender" id="optionsRadios1" value="1"
                                    onclick="condition_toggle(this.value);">
                                    Manual(Product Added Manualy)
                                  </label>
                                  <div style="clear:both"></div>
                                  <label class="radio">
                                    <input type="radio" name="gender" id="optionsRadios2" value="2"
                                    onclick="condition_toggle(this.value);">
                                    Automatic(products addition automated)
                                  </label>
                                </div>
                                <div class="controls" id="condition_div" style="display:none; border: 1px solid #cfcfcf; margin-top: 5px;">
                                  <div class="box-content">
                                          <fieldset>
                                            <legend><h6>Select Conditions</h6></legend>
                                            <div class="control-group" id="relation_container">
                                                <div id="relation-parent_0">
                                                    <div class="relation-left">
                                                    <select name="key[]" id="key_0" class="relation-select">
                                                        <option value="">Select Brand</option>
                                                        <option value="">Select Brand</option>
                                                    </select>
                                                    <select name="condition[]" id="condition_0" class="relation-select">
                                                        <option value="">Select Brand</option>
                                                        <option value="">Select Brand</option>
                                                    </select>
                                                    <input type="text" name="constraint[]" id="constraint_0" class="relation-input" 
                                                    data-provide="typeahead" data-items="2" style="" />
                                                    </div>
                                                    <div class="relation-right">
                                                    <button type="reset" class="btn">X</button>
                                                    </div>
                                                </div>
                                            </div>                            

                                          </fieldset>
                                          <button type="button" class="btn btn-primary" onclick="add_relation();">Add More</button>
                                    </div>
                                </div>
                            </div>  
                            <div class="form-actions">
                              <button type="submit" class="btn btn-primary">Save changes</button>
                              <button type="reset" class="btn">Cancel</button>
                            </div>
                          </fieldset>
                        </form>   

                    </div>

                </div><!--/span-->
                                <div>
                                                          <a href="<?php echo base_url();?>admin.php/collection">
                                                             <button class="btn btn-large btn-success">View collection Listings</button>
                                                          </a>

                                        </div>
            </div><!--/row-->



                    <!-- content ends -->
            </div><!--/#content.span10-->
                </div><!--/fluid-row-->

        <hr>

2 个答案:

答案 0 :(得分:1)

你可以使用像这样的jQuery构建内存html标签(这是你需要的部分内容)。

var i = 0;

var memtag = $('<div />', {
     'class' : 'relation-parent_' + i,
     html    : $('<div />', {
                   'class' : 'relation-left',
                   'id'    : 'relation_' + i,
                   html    : $('<select />', {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                             })
                )}
)};

// use variable memtag to insert html into the DOM
然而,嵌套使得它非常难以理解。如果这是您正在寻找的,您可以将标签分配给变量并稍后组合整个html结构。这是很多工作,而且不是很容易维护。

你也可以用例如Angular JS或其他框架

问题更新后更新

See this fiddle内部div已被取出并分配给变量。除了逗号分隔原始html中的多个对象外,您必须add它们,因为它们不是字符串而是对象。

    i = i + 1;

    var html1 = $('<div />', {
                   'class' : 'relation-left',
                   'id'    : 'relation_' + i,
                    html    : $('<select />', 
                                  {
                                 'class'  : 'relation-select',
                                 'id'     : 'key_' + i,
                                 'name'   : 'key[]'
                                  })
                });
    var html2 = $('<div />', {
                           'class' : 'relation-right',
                            html    : $('<button />', 
                                          {
                                         'class'  : 'btn',
                                         'name'   : 'btn[]'
                            })
                });

    var memtag = $('<div />', {
        'class' : 'relation-parent_' + i,
         html    : html1.add(html2)
    });

    $("#relation_container").append(memtag);

答案 1 :(得分:0)

如果您使用模板引擎,则可以轻松地将新ID作为JSON传递给模板。请检查以下代码。

注意:添加jquery模板库脚本引用和jquery库 对于Ref:https://github.com/BorisMoore/jquery-tmpl

<script id="SampleTemplate" type="text/x-jquery-tmpl">
    <div class="relation-parent_${Id}">
            <div class="relation-left" id="relation_${Id}">
            <select name="key[${Id}]" id="key_${Id}" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <select name="condition[${Id}]" id="condition_${Id}" class="relation-select">
                <option value="">Select Brand</option>
                <option value="">Select Brand</option>
            </select>
            <input type="text" name="constraint[${Id}]" id="constraint_${Id}" class="relation-input" data-provide="typeahead" data-items="2" style="" />
            </div>
            <div class="relation-reight">
            <button type="reset" class="btn">X</button>
            </div>
        </div>

</script>

并编译模板调用,如下所示

var NewId={"Id":1};
$("#SampleTemplate").tmpl(NewId).appendTo("#relation_container");