通过div来预告

时间:2013-03-08 16:21:49

标签: javascript jquery

我在通过以下构造进行循环时遇到了一些麻烦:

<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并读取所选选项和文本字段的值(select,to,away)。这样做,如果我只有一件事例如test1,那么查询没问题:

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

但是,如果我添加两个文本字段并希望为每个测试(1-3)执行此操作,我不知道......

有什么想法吗? 谢谢!

4 个答案:

答案 0 :(得分:3)

ID应该代表DOM中的唯一项目。改为使用类,如下所示:

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

答案 1 :(得分:0)

这个怎么样?

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

答案 2 :(得分: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');
});

答案 3 :(得分:0)

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

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

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

//now do for second and third also
}