2012-02-28 62 views
2

由于某些行通过克隆动态插入,因此我没有要查看的ID。jQuery遍历DOM - 单击按钮时按类别定位项目

我正在查找与检查系统按钮相对应的systemname的值被单击。

下面是函数:

function getSystemInfo(btn){  
    var buttonClicked = $(btn); 
    var firstSystemName = buttonClicked.parent().next().find($("input.systemname")); 
    alert($(firstSystemName).val()); 
}    

这里是生成的源代码:

<div name="singleSystemDiv" class="offset-bg"> 
    <div class="field inline"> 
    <label class="frmFlds_labels">System Name</label> 
    <input name="systemname" class="systemname" size="15" value="d1cti1d4" type="text"> 
    </div> 
    <div class="field inline"> 
    <label class="frmFlds_labels">Location</label> 
     <select id="location" name="location"> 
      <option value=""></option> 
      <option value="Akron">Akron</option> 
      <option value="Allen">Allen DC - Mob</option> 
      <option value="Alpharetta">Alpharetta - Mob</option> 
     </select> 
    </div> 
    <div class="field inline"> 
    <label class="frmFlds_labels">Platform</label> 
     <select id="platform" name="platform" onChange="updateModels(this);" class="platform"> 
      <option value=""></option> 
      <option value="IBM" selected="selected">AIX</option> 
     </select> 
    </div> 
    <div class="buttons"> 
     <input value="Remove System" onClick="removeSystemRow(this);" type="button"> 
     <input value="Check System" onClick="getSystemInfo(this);" type="button"> 
    </div> 
</div> 

我有这样的表述方式,我警报射击,不确定的。

我似乎不得不问很多关于遍历的SO问题。如果任何人有一个网站,说明这一点,请张贴。 jQuery关于.next(),parents()等的文档并不适合我。

+0

在看到Rory的答案后,我看到我的功能没有去到正确的父母级别。我需要更高。我需要更多地关注.closest()。谢谢Rory。 – HPWD 2012-02-28 15:27:00

回答

0

试试这个:

function getSystemInfo(btn){  
    var buttonClicked = $(btn); 
    var $firstSystemName = buttonClicked.closest("div[name='singleSystemDiv']").find($("input.systemname")); 
    alert($firstSystemName.val()); 
} 

Example fiddle

或者,你可以使用buttonClicked.parent().parent().find($("input.systemname"));,但我个人觉得链parent()要求有点难看。

+0

你不觉得'.closest(“。offset-bg”)'它有点可读性吗? – NicoSantangelo 2012-02-28 15:19:33

+0

所以不会让我把这个标记为正确的。我明白现在已经完成的解决方案,但我不确定我会想出.closest()。 – HPWD 2012-02-28 15:20:27

+0

@Nicosunshine我这样做,但是鉴于那个类名不是语义的,我不想依赖它始终在相对于按钮的正确div上。 – 2012-02-28 15:21:22