【发布时间】:2015-08-25 16:26:09
【问题描述】:
我有一个问题想弄清楚...
我在一个表单中有很多输入,但我只需要使用 player 类遍历 div 中的输入。
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
一旦修改了输入字段,我需要遍历它们,并计算有多少输入字段中有 0,如果它的 1 或超过 4 个禁用提交按钮。
我一直在尝试这样,但它似乎不起作用
$(document).ready(function()
{
$(function()
{
var $sum = parseInt($("#sum").text(), 10);
var $num = 0;
if(($sum == 0))
{
$("button[name=submit2]").attr("disabled", "disabled");
}
$(".player input[type=text]").bind("DOMSubtreeModified", function()
{
$.each($("input[type=text]"),function(){
if (!isNaN(+this.value))
{
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
});
})
});
我也试过了
$(document).ready(function(){
$(".unit").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".unit").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
【问题讨论】:
-
好吧,这个函数只会在加载时迭代。有没有试过把它做成自己的函数,然后在输入框的 onchange 属性中调用它?
-
你能解释一下你的代码返回什么导致它不能工作吗?
-
为什么还要迭代两次?你也可以像
$(".player .unit").keyup(function() {...那样做,以防止使用$.each
标签: javascript jquery html