2011-09-05 117 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