我有以下html表单,它是动态生成的:
<ul class="precursorList">
<li>
Precursor Name: <input name="precursorName" type="text">
<ul class="portList">
<li>Portname of precursor: <input name="precursorPort" type="text">
Portname of this: <input name="thisPort" type="text">
</li>
</ul>
</li>
<li>
<li>
Precursor Name: <input name="precursorName" type="text">
<ul class="portList">
<li>Portname of precursor: <input name="precursorPort" type="text">
Portname of this: <input name="thisPort" type="text">
</li>
</ul>
</li>
<li>
</ul>
我想使用jquery获取值,因此我定义了这个循环:
ports = [];
$(".precursorList :input").each(function() {
if(this.name == "precursorName") {
var precursorName_ = this.value
$(".portList :input ").each(function() {
if(this.name == "precursorPort") {
precursorPort_ = this.value;
} else if(this.name == "thisPort") {
ports.push({
filterName : precursorName_,
portNameOfFilter : precursorPort_,
portNameOfThis : this.value
});
}
});
}
});
不幸的是,这个功能不能像我希望它一样工作。以下循环$(".portList :input ").each(
将始终仅循环遍历html文档中portList中的所有元素。我怎样才能实现这个循环只会遍历相应的portList,对于每个前体?
UPDATE: html元素的结构将保持不变,输入数量将发生变化。但是如果存在PrecursorElement,则只会有一个portList。
答案 0 :(得分:0)
id
必须是唯一字段,而是使用class
选择多个元素。还可以使用.live()
来动态添加元素
修改强>
如果您正在使用Jquery&gt; 1.7使用.on()
代替.live()
我试过跟随它似乎正在工作
$(".precursorPort").each(function() {
temp = this.name;
$(this).parents(".portList").each(function() {
$(this).parents(".precursorList").each(function() {
alert(temp);
// use temp var and save it in ports
});
});
});
检查这个小提琴:http://jsfiddle.net/Ajinkya_Parakh/DR233/
它可能不是最好的/最有效的,但它是可行的替代方案之一。
答案 1 :(得分:0)
id
必须在文档中是唯一的。如果你想创建一组类似的东西,那就改用一个类。
答案 2 :(得分:0)
我会做这样的事情:
<ul id="precursorList">
<li>
Precursor Name1: <input class="precursor" name="precursorName1" id="precursorName1" type="text">
<ul id="portList1">
<li>Portname of precursor1: <input class="precursorPort" name="precursorPort1" id="precursorPort1" type="text">
Portname of this1: <input class="thisPort" name="thisPort1" id="thisPort1" type="text">
</li>
</ul>
</li>
<li>
Precursor Name2: <input class="precursor" name="precursorName2" id="precursorName2" type="text">
<ul id="portList2">
<li>Portname of precursor2 <input class="precursorPort" name="precursorPort2" id="precursorPort2" type="text">
Portname of this2: <input class="thisPort" name="thisPort2" id="thisPort2" type="text">
</li>
</ul>
</li>
</ul>
然后:
ports = [];
$("#precursorList > li").each(function()
{
precursor = $(this).find(".precursor")[0];
precursorPort = $(this).find(".precursorPort")[0];
thisPort = $(this).find(".thisPort")[0];
ports.push({filterName: precursor.value, portNameOfFilter: precursorPort.value, portNameOfThis: thisPort.value});
});
答案 3 :(得分:-1)
在<form>
代码中包装动态表单。然后做一个$('form').serialize()
不需要疯狂的循环。 Serialize本质上是您已经尝试做的内置的单行版本。当然,序列化对名称起作用,所以你必须有不同的名称(即使它只是name1,name2等)ID也必须是唯一的,所以要么修复它,要么放弃它们。
简单性总是胜过疯狂的技术天才。