微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Jquery.每个不工作,坏代码或更好的方法可用吗?

首先是设置:
jquery 1.5.1
Firefox 4.0

目标:
我有一堆使用复选框启用/禁用的文本框.如果启用了文本框,我希望它的值大于零.

其中一个框的HTML(页面上有可变数量的框):

<input type="text" value="0" name="RequestList[4].iCount" id="RequestList_4__iCount" class="num-Box">

我的jQuery使用.each不起作用:

var oneFill = false;
$('.num-Box').each(function() {
    var myItem = $(this);
    if (myItem.attr('disabled') == false) {
        if (myItem.val() > 0) {
            oneFill = true;
        }
    }
});
if (!oneFill) {

当我在Firebug中跟踪上面的代码时,它什么也没做.它继续到下一行代码(if(!oneFill)).

当我在Firebug中使用$(‘.num-Box’)时,它会返回所有文本框的完整列表.所以我非常有信心我有正确的选择器.

所以问题是,我做错了什么?我在这里看了很多例子,似乎我对.each的使用是正确的.

但是,有没有更有效的方法来检查所有启用的文本框与num-Box类?

Addition1
@artlung
使用上面的示例html继续,我至少会有以下内容

<input type="text" value="0" name="RequestList[1].iCount" id="RequestList_1__iCount" class="num-Box">
<input type="text" value="0" name="RequestList[2].iCount" id="RequestList_2__iCount" class="num-Box">
<input type="text" value="0" name="RequestList[3].iCount" id="RequestList_3__iCount" class="num-Box">
<input type="text" value="0" name="RequestList[4].iCount" id="RequestList_4__iCount" class="num-Box">

复选框看起来像:

<input type="checkBox" value="true" name="RDEquipListItem[1]" id="RDEquipListItem_1_">
<input type="checkBox" value="true" name="RDEquipListItem[2]" id="RDEquipListItem_2_">
<input type="checkBox" value="true" name="RDEquipListItem[3]" id="RDEquipListItem_3_">
<input type="checkBox" value="true" name="RDEquipListItem[4]" id="RDEquipListItem_4_">

我有java脚本,当选中相应的复选框时,启用/禁用文本框.

到目前为止,我已经看到了对我的代码的一些很好的调整.我明天会投票给那些人.

我的困惑是我的.each部分是否存在问题:

$('.num-Box').each(function() {

Addition2
我一直在玩一些结果.我目前的代码如下:

var oneFill = false;
var myEnabled = $('.num-Box:enabled');
myEnabled.each(function() {
    var myItem = $(this);
    if (parseInt(myItem.val()) > 0) {
        oneFill = true;
    }
});
if (!oneFill) {

myEnabled获取正确启用的元素列表.竖起大拇指

但是,myEnabled.each什么也没做.

.each使用的单个项目是否存在问题?

最后评论
不知道为什么这给了我一个问题,但我不得不重新排序逻辑.即使使用Firebug,它也不会进入“.each”代码,但结果是正确的.

最终代码(注意:.num-Box是由复选框启用/禁用的文本框):

//make sure one item has been filled in and all are greater than zero
var allFilled = true;
var myEnabled = $('.num-Box:enabled');
//check that we have at least one item checked out
if (myEnabled.length == 0) {
    alert("At least one needs to be filled.");
    return false;
}

$.each(myEnabled,function() {
    var myItem = $(this);
    if (parseInt(myItem.val()) <= 0) {
        allFilled = false;
    }
});
if (!allFilled)
{
    //go do something

解决方法

试试这个

var oneFill = false;
$('.num-Box').each(function() {
    var myItem = $(this);
    if (myItem.is(":enabled") && parseInt(myItem.val()) > 0) {
            oneFill = true;

    }
});
if (!oneFill) {
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐