一个类型的jQuery .prev(),而不管它是父类等 [英] jQuery .prev() of a type regardless of it's parent etc

查看:149
本文介绍了一个类型的jQuery .prev(),而不管它是父类等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方式来获取DOM中之前发生的元素?如果我正在查看#text3 ,我想要保留以前的输入#text2

 < div> 
< input id =text1type =textvalue =text1/>
< / div>

< div>
< p>选择你的比赛!< / p>
< input id =text2type =textvalue =text2/>
< / div>

< div>
< div class =labeledField>
< label>文本3:< / label>
< input id =text3type =textvalue =text3/>
< / div>
< / div>

.prev('input')不工作,因为它在父母和 .prevAll('input')似乎只搜索父母...我在这里缺少一些东西?这个感觉就好比应该比 $('#text3)更容易。parent()。prev()。find('input'):D

解决方案

您可以使用 $。index() ,如下所示:

 code> var previous = null; 
var inputs = $('input');
var index = inputs.index(this);
if(index> 0){
previous = $(inputs [index-1])$ ​​b $ b}

例如: http://jsfiddle.net/pYaBL / 1 /


is there a simple way to get the previous occurrence of an element in the DOM? If I'm looking at #text3 and I want to get ahold of the previous input #text2.

<div>
    <input id="text1" type="text" value="text1" />
</div>

<div>
    <p>Choose your race!</p>
    <input id="text2" type="text" value="text2" />
</div>

<div>
    <div class="labeledField">
        <label>Text 3:</label>
        <input id="text3" type="text" value="text3" />
    </div>
</div>

.prev('input') doesn't work cause it's within the parent and .prevAll('input') seems to only search the parent as well... Am I missing something here? This feels like it should be much easier than $('#text3').parent().prev().find('input') :D

解决方案

You can use $.index(), like so:

var previous = null;
var inputs = $('input');
var index = inputs.index(this);
if (index > 0) {
    previous = $(inputs[index-1])
}

For example: http://jsfiddle.net/pYaBL/1/

这篇关于一个类型的jQuery .prev(),而不管它是父类等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆