2013-03-08 33 views
1

我有关于通过下面的结构做一个循环了一些麻烦:的foreach通过DIV

<div id="items"> 
    <p id="test1"> 
     <select name="1" id="1"><option>A</option><option selected>B</option></select> 
     <input type="text" name="to" id="to"> 
     <input type="text" name="away" id="awy"> 
    </p> 
    <p id="test2"> 
     <select name="2" id="2"><option>A</option><option selected>B</option></select> 
     <input type="text" name="to" id="to"> 
     <input type="text" name="away" id="awy"> 
    </p> 
    <p id="test3"> 
     <select name="3" id="3"><option>A</option><option selected>B</option></select> 
     <input type="text" name="to" id="to"> 
     <input type="text" name="away" id="awy"> 
    </p> 
</div> 

我需要通过TEST1,TEST2和TEST3运行和读取所选择的选项和文本字段的值(选择,去掉)。这样做,如果我在,例如test1的只拿到了一件事与查询没有问题:

$('#items').children('p').each(function() {...} 

但是,如果我添加了两个文本字段,并希望每个测试做到这一点(1-3)我没有想法...

任何想法? 谢谢!

+9

ID必须是唯一的。 – SLaks 2013-03-08 16:22:53

+0

向我们展示函数中的代码! – Bergi 2013-03-08 16:24:11

+0

ids必须是唯一的...和有效的NCName我认为:http://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-NCName(必须以字母或下划线开头) – Vinze 2013-03-08 16:26:55

回答

0

这个怎么样?

$('#items').find('select option:selected, input:text').each(function(){ 
     alert($(this).val()); //Value of each selected option and text field within the div 
}); 
3

ID应代表DOM中的唯一项。使用类代替,就像这样:

<input type="text" name="to" class="to"> 
<input type="text" name="away" class="awy"> 
0

你甚至需要做.children部分。

试试这个:

$('#items > p').each(function() { 
    // you can then use $(this) to reference the currently iterated p element. 
    // such as $(this).find('input[type="text"]:first'); 
    // or 
    // $(this).find('input[type="text"]:last'); 
}); 
+0

为什么不呢?你的是一个不同的选择器,顺便说一句。 – Bergi 2013-03-08 17:07:51

+0

对不起,编辑! – 2013-03-08 17:21:22

0

注意:首先给的唯一ID的所有元素。

以下代码可能对您有所帮助。

$(‘p’).each(function(index){ 
this.children().get(0).val(); 

//now do for second and third also 
} 
+0

''''不是有效的字符串分隔符 – Bergi 2013-03-08 17:06:41