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

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

本文关键字:数据 对象 何创建 创建 动态控件      更新时间:2023-09-26

创建了一个div和一个按钮。当点击按钮时,会有一组元素(包括1个选择框和2个文本输入)插入到div中。用户可以添加尽可能多的组,当他们输入完他们添加的所有组的数据时,他可以点击保存按钮,它会将每个组的值逐个放入JSON对象数组中。但是我被困在如何从每个组中获得价值的部分,所以请帮助,谢谢。

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

这应该就可以了。但是,如果动态创建这些组,则需要使用id以外的其他名称。您可能希望向它们添加一个类或一个data-*属性。在这里,我使用了一个类。将这些类添加到控件中,这样我们就知道哪个是哪个了。

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

最好不要使用id属性来标识选择和输入,而应该使用name属性。例如

 $('#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>');
 }

,然后使用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
 });

常见问题。几件事:

  1. 你不能在你要重复的部分使用id,因为DOM中的id应该是唯一的。

  2. 我更喜欢在我写了很多标记的地方使用标记,并在代码中修改它,而不是在那里生成它。

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

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:

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

因此,不断重复的模板是用普通的旧HTML编写的,而不是一堆JS字符串相互附加。使用name属性而不是id保持了这些元素通常的工作方式,而不违反任何DOM约束。

您可能会注意到我没有引用属性,将值属性从选项中取出,并将类型属性从输入中取出,以使代码更简洁。HTML5规范不需要引用你的属性,选项标签的值是文本,如果你没有明确指定一个值属性,输入标签默认为type=text,如果没有指定,所有这些加起来更快阅读和精简的HTML。

使用$(".extra"). each函数(){

//从这里的控件中拉出信息

});

这将遍历所有额外的div,并允许您将所有值添加到数组中。