2011-09-05 46 views
1

我的表單有多個輸入元素。當我循環瀏覽一些元素時,我需要找到下一個div中的下一個元素的id找到下一個div中存在的下一個元素的id -jquery

整個代碼是jsfiddle

$(":text[name^=sedan]").each(function(i){ 
var curTxtBox = $(this); 
var curId = this.id; 
alert(curId); 
    //var nextTextFieldId = $(this).closest('div').find('.number').attr("id"); // gives undefined 
    var nextTextFieldId = $('#'+curId).next('div:input[type=text]').attr("id"); // gives undefined 
    alert(nextTextFieldId) 

}); 

這是行不通的。 nextTextFieldId給出的值未定義。

HTML

<div class="first"> 
    <div class="second"> 
     <input type="text" class ="myClass" name="sedan1" id = "sedan1" value="1" /> 
    </div> 
    <div class="third"> 
     <input type="text" class ="yourClass" name="suv1" id ="suv1" value="2"/> 
    </div> 
</div> 
<div class="first"> 
    <div class="second"> 
     <input type="text" class ="myClass" name="sedan2" id = "sedan2" value="3" /> 
    </div> 

    <div class="third"> 
    <input type="text" class ="yourClass" name="suv2" id = "suv2" value="" /> 
    </div>   
</div> 
+0

然後不要使用'each'。您已經擁有了jQuery對象中所需的所有元素,因此只要使用'results.get(i + 1)'來訪問「下一個」文本框時,只需執行'for'循環即可。你在這裏做的是讓自己變得更加困難。 – Jon

+0

可以代碼嗎? – maaz

+0

請看下面的答案。您可能需要根據需要對其進行修改。 – Jon

回答

4
var nextTextFieldId = $(this).parent().next().find(':text').attr("id"); 
0

嘗試改變這一行:

var nextTextFieldId = $('#'+curId).parent().next('div:input[type=text]').attr("id"); // gives undefined 

你行預計,輸入標籤有一個兄弟div標籤。

+0

undefined ...伊戈爾Dymovs答案是完美的! – maaz

+0

@Hussain:我希望你意識到,Igor的答案在下次更改HTML佈局時將停止工作。 – Jon

1

擴大我的評論(總結:不這樣做,只是遍歷jQuery對象與for和快樂)到一個答案:

$(document).ready(function(){ 
    var $textBoxes = $(":text[name^=sedan]"); 
    for(var i = 0; i < $textBoxes.length; ++i) { 
     var $curTxtBox = $textBoxes.eq(i); 
     alert($curTxtBox.attr("id")); 
     if (i < $textBoxes.length - 1) { 
      var nextTextBoxId = $textBoxes.eq(i + 1).attr("id"); 
      alert(nextTextBoxId); 
     } 
     else { 
      // This was the last one, there is no "next" textbox 
     } 
    } 
}); 

需要注意的是:

  1. 以這種方式做事並不需要像使用each(最終多次在樹中搜索相同元素)的天真方法一樣隨時行走DOM樹。
  2. 只要您保留sedanXX ID,此方法將正常工作。只要HTML發生重大變化,重新遍歷DOM樹的方法就會中斷。
  3. 如果所有你想要的是id的,並且它們遞增整數,即使這是矯枉過正。
+0

看起來不像優化的一個...伊戈爾斯回答是作品一種享受! – maaz

+0

@Hussain:我會在這裏留下這個「未優化」的答案,因爲我懷疑你可能會在將來發現它有用。別客氣。 – Jon

+0

感謝您的親切信息喬恩..我真的很感激你.. – maaz