0

我想对.change()价值变化做出反应。在这种情况下,必须更新另一个(隐藏的)字段。

<input type="text" name="n1"><br>
<input type="text" name="n2"><br>
<input type="text" name="n3"><br>    
<input type="hidden" name="h1"><br>
<script>
$("input[type='text']").change( function() {

 try {
     $temp = $(this).next("input[type='hidden']");
 } catch (e) { // just for testing
     alert("not found "+e);
} 
 try {    
     $temp = $(this).next("input[name='h1']");
} catch (e) { { // just for testing
     alert("not found "+e);
}     
 $temp.val("hidden");
 alert("Temp is a "+$temp);
    alert("Temp has following value:"+$temp.val());

})
</script>

用于测试的演示:http: //jsfiddle.net/22C2n/1209/

这个说法

$temp = $(this).next("input[type='hidden']");

导致“未定义”,或者更好: $temp 是 $object[] 而不是(作为方面) $object[ input name='h1']

问题出在哪里?

4

2 回答 2

1

你需要使用.nextAll()然后你会找到你正在寻找的元素。

$(this).nextAll("input[type='hidden']");

演示

于 2013-08-13T07:55:39.893 回答
0

使用 nextAll(),并小心你的 catch 块(那些在小提琴中的 ;))。

我不会使用两个 try/catch 块,因为即使在第一个块中填充了 $temp,它也会被第二个块覆盖。

请注意,仅当输入失去焦点时才会触发更改事件。

我更新了你的小提琴:

$temp = $(this).nextAll("input[type='hidden']");
if($temp.length <= 0) $temp = $(this).nextAll("input[name='h1']");

在此处查看演示

于 2013-08-13T08:08:27.473 回答