【发布时间】:2015-06-24 15:24:39
【问题描述】:
我有一个包含多个输入的表单,以及它们旁边(左侧)的相应标签。
当我验证输入时,我想使用相应的标签显示一条消息,以判断哪个输入是错误的。
我有一个工作脚本显示我想要的标签,但如果我的输入不是标签的直接兄弟,而是兄弟的孩子,它会中断......
下面是代码来说明:
HTML:
<form>
<label class="autoFormLabel obligatorio">* calle : </label>
<input id="calle2" class="autoForm obligatorio" type="text" value="" name="calle2">
<br>
<label class="autoFormLabel obligatorio">* CP : </label>
<input id="CP" class="autoForm obligatorio" type="text" value="" name="CP">
<br>
<label id="label_colonia" class="autoFormLabel obligatorio">* Colonia : </label>
<span id="span_combo_colonias">
<select id="Colonia" class="obligatorio autoForm" name="Colonia">
<option selected="" value="0">-- seleccione --</option>
<option value="1">one</option>
<option value="2">two</option>
</select>
</span>
<br>
<label class="autoFormLabel obligatorio">* Delegacion : </label>
<input id="delegacion" class="autoForm obligatorio" type="text" value="" name="delegacion" >
<br>
<input type="button" id="val" value="Val" />
</form>
JS:
function validate(){
$(":input.obligatorio:enabled").each(function( i, el ){ // solo considerar los enableds
if( $(this).val() == "" || $(this).val() == "0" || $(this).val() == 0){
label = $(this).prev("label").html(); //A: works for all but select
//label = $(this).parent().prev("label").html(); //B: works for select, but not the others
//label = $(this).closest("label").html(); //C: why doesn't work for select?
alert("El campo:\n\n"+label+"\n\nno puede ir vacio");
$(this).focus();
return false;
}
});
}
所有输入都有一个对应的兄弟标签,除了 <select>,它位于 <span> 内,它本身就是其标签的兄弟标签。
我的选择器 label = $(this).prev("label").html(); 非常适合选择的所有输入 excpet,因为它包含在一个跨度内(我需要这样,因为这样的选择是动态的,并且通过 AJAX 插入到这样的跨度内)
我知道我可以让它与另一个选择器一起工作,例如:label = $(this).parent().prev("label").html();
但理想情况下,我希望只有一个选择器来获取所有标签,无论它们对应的输入有多深。
我也尝试使用 .closest() 选择器,但它不起作用,我不知道为什么,但我认为它没有,因为标签不是 select 的升序(它是兄弟它的父母,[比方说“叔叔”])
那么我可以在所有情况下使用哪个选择器,以获取最接近输入的先前标签,尽管是父母、兄弟姐妹、父母兄弟姐妹甚至是祖祖父母,无论如何......(我可以隐藏在其标签旁边的几个跨度内的输入,或其他)
换句话说,我怎样才能遍历“左上方”的 DOM 并获得选择器的第一次出现,无论它们是父级还是兄弟级?
【问题讨论】:
-
@nirmal,小提琴已经在那里了。
-
@Nimal 问题完整且清晰
-
@mplungjan 看来您的解决方案不起作用。我试过here。也许我做错了什么?谢谢
标签: jquery jquery-selectors dom-traversal