简体   繁体   English

如何创建动态控件并将其数据放入对象?

[英]How can I create dynamic controls and put their data into an object?

I created a div and a button. 我创建了一个div和一个按钮。 when the button clicked, there will be a group of element(included 1 select box and 2 text inputs) inserted into the div. 单击按钮时,将有一组元素(包括1个选择框和2个文本输入)插入div。 User can add as many group as they can, when they finished type in data of all the group they added, he can hit save button, which will take the value from each group one by one into the JSON object array. 用户可以添加尽可能多的组,当他们输入添加的所有组的数据时,他可以点击保存按钮,它将每个组的值一个接一个地输入到JSON对象数组中。 But I am stuck in the part how to get the value from each group, so please help, thank you. 但是我仍然停留在如何从每个小组中获得价值的部分,所以请帮助,谢谢。

The code for the div and the add group button function -- AddExtra() are listed below: 下面列出了div和添加组按钮功能的代码-AddExtra():

<div id="roomextra">
</div>

function AddExtra() {
$('#roomextra').append('<div class=extra>' +
'<select id="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' + 
'Length(m): <input type="text" id="insetLength">' +
'Width(m): <input type="text" id="insetWidth">' +
'Height(m): <input type="text" id="insetHeight">' +
'</div>');
}

function GetInsetOffSetArray (callBack) {

  var roomIFSDetail = [{
   "IsInset": '' ,
   "Length": '' , 
   "Width": ''  , 
   "Height": ''
  }];

//should get all the value from each group element and write into the array.

callBack(roomIFSDetail);

}

This should just about do it. 这应该就做。 However, if you're dynamically creating these groups, you'll need to use something other than id. 但是,如果要动态创建这些组,则需要使用id以外的其他名称。 You may want to add a class to them or a data-* attribute. 您可能要向它们添加一个类或data-*属性。 I used a class, in this case. 在这种情况下,我使用了一个类。 Add those classes to your controls so we know which is which. 将这些类添加到您的控件中,以便我们知道哪个。

var roomIFSDetail = [];
var obj;

// grab all of the divs (groups) and look for my controls in them
$(.extra).each(function(){
  // create object out of select and inputs values
  // the 'this' in the selector is the context. It basically says to use the object
  // from the .each loop to search in. 
  obj = {
           IsInset: $('.isInset', this).find(':selected').val() ,
           Length: $('.insetLength', this).val() ,
           Width: $('.insetWidth', this).val() , 
           Height: $('.insetHeight', this).val()
        }; 
  // add object to array of objects
  roomIFSDetail.push(obj);
});

you'd better not to use id attribute to identity the select and input, name attribute instead. 您最好不要使用id属性来标识选择和输入name属性。 for example 例如

 $('#roomextra').append('<div class=extra>' +
     '<select name="isInset">' +
     '<option value="Inset">Inset</option>' +
     '<option value="Offset">OffSet</option>' +
     '</select>' + 
     'Length(m): <input type="text" name="insetLength">' +
     'Width(m): <input type="text" name="insetWidth">' +
     'Height(m): <input type="text" name="insetHeight">' +
     '</div>');
 }

and then, usr foreach to iterate 然后,usr foreach进行迭代

 $(".extra").each(function() {
     var $this = $(this);
     var isInset = $this.find("select[name='isInset']").val();
     var insetLength = $this.find("input[name='insetLength']").val();
     // ... and go on
 });

A common problem. 常见问题。 A couple things: 几件事:

  1. You can't use IDs in the section you're going to be repeating, because IDs in the DOM are supposed to be unique. 您不能在要重复的部分中使用ID,因为DOM中的ID应该是唯一的。

  2. I prefer to use markup where I'm writing a lot of it, and modify it in code rather than generate it there. 我更喜欢在要编写大量标记的地方使用标记,并在代码中对其进行修改,而不是在此处生成标记。

http://jsfiddle.net/b9chris/PZ8sf/ http://jsfiddle.net/b9chris/PZ8sf/

HTML: HTML:

<div id=form>
... non-repeating elements go here...

<div id=roomextra>
<div class=extra>

<select name=isInset>
<option>Inset</option>
<option>OffSet</option>
</select>
Length(m): <input id=insetLength>
Width(m): <input id=insetWidth>
Height(m): <input id=insetHeight>

</div>
</div>

</div>

JS: JS:

(function() {
// Get the template
var container = $('#roomextra');
var T = $('div.extra', container);

$('#addGroup').click(function() {
    container.append(T.clone());
});

$('#submit').click(function() {
    var d = {};
    // Fill d with data from the rest of the form

    d.groups = $.map($('div.extra', container), function(tag) {
        var g = {};
        $.each(['isInset', 'insetLength', 'insetWidth', 'insetHeight'], function(i, name) {
            g[name] = $('[name=' + name + ']', tag).val();
        });

        return g;
    });

    // Inspect the data to ensure it's what you wanted
    debugger;
});

})();

So the template that keeps repeating is written in plain old HTML rather than a bunch of JS strings appended to each other. 因此,不断重复的模板是用普通的旧HTML编写的,而不是一堆彼此附加的JS字符串。 Using name attributes instead of ids keeps with the way these elements typically work without violating any DOM constraints. 使用名称属性代替id可以保持这些元素通常的工作方式,而不会违反任何DOM约束。

You might notice I didn't quote my attributes, took the value attributes out of the options, and took the type attributes out of the inputs, to keep the code a bit DRYer. 您可能会注意到,我没有引用我的属性,没有从选项中删除了value属性,而从输入中删除了type属性,以使代码保持干燥。 HTML5 specs don't require quoting your attributes, the option tag's value is whatever the text is if you don't specify a value attribute explicitly, and input tags default to type=text if none is specified, all of which adds up to a quicker read and slimmer HTML. HTML5规范不需要引用属性,如果未明确指定value属性,则option标签的值就是文本,而如果未指定,则输入标签默认为type = text,所有这些加起来就是更快的阅读速度和更薄的HTML。

Use $(".extra").each(function() { 使用$(“。extra”)。each(function(){

//Pull info out of ctrls here //在此处从ctrl中提取信息

}); });

That will iterate through all of your extra divs and allow you to add all values to an array. 这将遍历所有额外的div,并允许您将所有值添加到数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM