jquery - 通过不同的功能保持计数一致

标签 jquery forms

您好,我正在使用以下代码将文件输入添加到我的表单中:

var addFile = document.getElementById('addFile');
addFile.onclick = function addFile() {
    if (this.count == undefined) {
        this.count = 0;
    }
    if (this.count++ < 2) {
        $(".files").append('<tr><td><input type="file" name="uploaded_file[]" class="file_input" size="46" style="margin-top:1px;"/><a class="delete" href="javascript:void(0)" style="color:blue; padding-left:15px;">Remove File</a></td></tr>');
    }
    if (this.count == 2) {
        alert('If you wish to upload more than 3 files \nplease compile them into a .zip or .rar file');
    }
};

以下代码用于删除文件输入。

$(function () {
    $(".delete").live("click", function () {
        $(this).parent().remove();
    });
});

我正在寻找一种可能将两者结合起来的方法,其中当我删除文件时,总体输入计数为-1,就像添加时为+1一样。这样,如果用户添加一个槽位,然后删除一个槽位,然后重新添加一个槽位,则计数是一致的。欢迎任何帮助。

干杯

最佳答案

不要存储和保留计数,而是每次获取计数。

addFile.onclick = function addFile() {
    var count = $(".files tr .file_input").length;
    if ( count < 3 ) {
        // append the row
    }
    else {
        // don't append the row
    }
}

效率可能稍低,但更易于管理。

关于jquery - 通过不同的功能保持计数一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12185605/

相关文章:

javascript - 使用 Bootstrap 模态代替 Colorbox

jQuery:防止按钮/单击事件上的表单提交

python - Django 模型表单 - 动态创建字段的顺序

jquery - 排除周末可在 jQuery 日期选择器上点击

jquery - 滚动魔法 : Add offset to anchor scrolling?

javascript - 将变量名称作为参数传递给另一个函数后,我可以将其作为字符串访问吗?

即使用户名/密码很短/很长或密码不匹配,PHP 注册表也会将数据写入数据库。要改变什么?

javascript - 使用 promises 获取 ajax 数据

javascript - 表单提交后运行脚本和php

javascript - React.js - 如何设置选中/选中的单选按钮并跟踪 onChange?