2012-02-28 61 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