javascript - Jquery Prop 功能未按预期工作

标签 javascript jquery

我正在尝试根据一些计算和使用 jquery 启用/禁用一些隐藏字段 prop 函数,这里是代码

function enableSelectedFieldsData(count, mapKey, index) {
    $("#code_" + mapKey + "_" + index).prop("disabled", false);
    $("#description_" + mapKey + "_" + index).prop("disabled", false);
    $("#crossRefrence_" + mapKey + "_" + index).prop("disabled", false);
    $("#image_" + mapKey + "_" + index).prop("disabled", false);
    $("#price_" + mapKey + "_" + index).prop("disabled", false);
    // disable all other fields
    for (var i = 0; i < count; i++) {
        if (i != index) {
            $("#code_" + mapKey + "_" + i).prop("disabled", true);
            $("#description_" + mapKey + "_" + i).prop("disabled", true);
            $("#crossRefrence_" + mapKey + "_" + i).prop("disabled", true);
            $("#image_" + mapKey + "_" + i).prop("disabled", true);
            $("#price_" + mapKey + "_" + i).prop("disabled", true);
        }
    }
}

最初我为所有字段设置 disable=true 并根据选择我尝试启用选定字段同时禁用其他字段,因为据我所知禁用字段从未在提交表单时提交给服务器,但在我以防他们被提交。

在使用 Firebug 进行检查时,我看到非选定项目的禁用字段值被设置为 "",如 disable=""

我不确定我在哪里设置错误,在这方面的任何帮助或指示都会很有帮助。

编辑

我已从生成的 HTML 中取出相关部分并将其放置在 jsfiddle。 请看一下

最佳答案

你有可用的 prop() 吗?

prop() 是在 jQuery 1.6 中添加的,使用方式如下:

$("input").prop('disabled', true);
$("input").prop('disabled', false);

如果您使用的是 jQuery 1.5.x 或更低版本,您可以使用 attr() 代替,如 FAQ - How to enable/disable form elements 中所示来自 jQuery 网站:

// Disable #x
$('#x').attr('disabled', true);

// Enable #x
$('#x').attr('disabled', false);

// -- or --

// Disable #x
$("#x").attr('disabled', 'disabled');

// Enable #x
$("#x").removeAttr('disabled');

假设您使用的是 jQuery 1.6 或更高版本

您的语法看起来不错。 我猜你的问题很可能是不正确的选择器。

要验证选择器是否包含您期望的元素引用:

 // output the selector to the console
console.log($("#code_" + mapKey + "_" + index));

如果您在浏览器的调试控制台中看到一个元素,那么您正在寻找一个有效的选择器,如果您看到的是 [],那么您的选择器是无效的。

或者,您可以使用 length 属性检查它并发出警告:

// alert out the length of the jQuery selector
alert($("#code_" + mapKey + "_" + index).length);

如果您看到 0 则您的选择器无效,如果您看到 1 或更多则您的选择器是正确的。

关于javascript - Jquery Prop 功能未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12387786/

相关文章:

javascript - 字符串操作的Nodejs内存不足错误

jquery - 折叠和展开部分,未显示图像

jQuery - 功能设置

javascript - 禁用网页上的所有滚动

javascript - 检查下拉列表中的重复值

javascript - 当页面上已有旧版本时,如何在 chrome 扩展内容脚本中使用 jquery

javascript - ";"是必须的吗?

javascript - 从 DOM 中提取字符串时,字符串的处理方式有所不同

javascript - 没有表格的 Dropzonejs

javascript - 脚本 70 : Permission denied when adding options to select element from a recently closed iframe