如何使用id获取特定兄弟元素的值

sah*_*har 1 jquery siblings

我想使用id获取特定兄弟元素的值,我在运行时构建表单,并且有许多元素具有相同的id但在不同的部分.我试图使用$(this).siblings("#BillNo").val(); $(本).prev( "#BillNo")VAL().但两者都返回未定义的值

这个代码在运行时:佣金

<div id="bill1" class="bill hide withPadding">
    <h3>Bill 1</h3>
    <span>
    <label>Bill no</label>
    <input type="text" name="billNo" class="textField" id="BillNo"/>
    </span>
    <span>
    <label>Bill total</label>
    <input type="text" name="billTotal" class="textField" id="BillTotal"/>
    </span>
    <span>
    <input type="button" name="addBillDetails" value="Add bill items" id="addBillDetails"/>
    </span>
</div>  

<div id="bill2" class="bill hide withPadding">
    <h3>Bill 2</h3>
    <span>
    <label>Bill no</label>
    <input type="text" name="billNo" class="textField" id="BillNo"/>
    </span>
    <span>
    <label>Bill total</label>
    <input type="text" name="billTotal" class="textField" id="BillTotal"/>
    </span>
    <span>
    <input type="button" name="addBillDetails" value="Add bill items" id="addBillDetails"/>
    </span>
</div>  

<script type="text/javascript">
$(document).ready(function() {
   $("input#addBillDetails").live('click',function(){
        alert($(this).siblings("#BillNo").val());
        alert($(this).prev("#BillNo").val());

        });
}
</script>
Run Code Online (Sandbox Code Playgroud)

Sha*_*hin 7

$('#BillNo', $(this).closest("div.bill")).val()
Run Code Online (Sandbox Code Playgroud)

这限制了#BillNo父div 的搜索.这是一个演示.


另外,您应该重新考虑HTML.id最好应是唯一的值.来自HTML4规范:

id = name [CS]

此属性为元素指定名称.该名称在文档中必须是唯一的.

HTML5规范:

id属性指定其元素的唯一标识符(ID).该值必须在元素的主子树中的所有ID中唯一,并且必须至少包含一个字符.该值不得包含任何空格字符.

例如,您可以使用类来区分不同的输入.定位它们同样容易.例如http://jsfiddle.net/HxtfP/1/.

或者,只需省略id并使用name属性进行定位:http://jsfiddle.net/HxtfP/2/