此代码存在多个问题。我将从html开始:
<div class="control-group" id="ports">
<label class="control-label" for="dataport1">dataport</label>
<!-- ^ no underscore, which means this won't work correctly -->
<div class="controls">
<input type="text" id="dataport_1" name="dataport_1" placeholder="Type something">
</div> <!-- end controls -->
</div><!-- end control-group-->
<div class>
<!-- ^ the class attribute without a value. While it may not cause parsing issues, its good to fix this anyway if you aren't going to use it -->
<a class="btn btn-primary pull-right" id="addportbtn">Add Another Port</a>
</div>
现在的javascript:
function addPorts()
{
var count = 2; // Every single one of these variables is local to the function
var numports = 2; // And thus cannot be accessed, and are re-initialized
var idnum; // every time the function is called
// ^ this variable is not incremented, so it will always be undefined
$('#addportbtn').click(function() { // and on that note, every time addPorts()
//alert(count); // called, it attaches another click
numports = idnum; // handler
var addHtml = '<div class="control-group">' +
'<label class="control-label" for="dataports">data port</label>'+ //this label won't attach to the input, as there is no input with the id of 'dataports'
'<div class="controls">'+
'<input type="text" id="dataport_idnum" placeholder="Type something">'+ //idnum is not parsed, strings are not parsed into variables. You must escape them first.
'</div> <!-- end controls -->'+
'</div><!-- end cotrol-group-->'
$( "#ports:last" ).after(addHtml);
numports = numports + 1; //again, variables are local to function, so doing this doesn't do anything
count++; // is pointless, isn't used.
}); //end click
}
而现在,修复...
如下链接的 serialize 方法通常应用于表单,而不是 div。
<form id="ports">
<div class="control-group">
<label class="control-label" for="dataport_1">data port</label>
<div class="controls">
<input type="text" id="dataport_1" name="dataport_1" placeholder="Type something" />
</div>
<!-- end controls -->
</div>
<!-- end control-group-->
<div> <a class="btn btn-primary pull-right" id="addportbtn">Add Another Port</a>
</div>
</form>
jQuery 的.serialize()
方法从元素的 name 属性中运行,因此要使其工作,必须指定它:
var numports = 2; // make variable global, so it can be accessed by any function
$(function () { //execute on dom ready, so events are bound correctly.
$('#addportbtn').click(function () {
var addHtml = '<div class="control-group">' +
'<label class="control-label" for="dataport_' + numports + '">data port</label>' +
'<div class="controls">' +
'<input type="text" id="dataport_' + numports + '" name="dataport_' + numports + '" placeholder="Type something"/>' +
// ^ name specified
'</div> <!-- end controls -->' +
'</div><!-- end cotrol-group-->'
$("#ports .control-group:last").after(addHtml);
numports++;
});
});
现在,当表单被序列化时,它将正确添加相关的输入字段。
这是一个工作演示。