2024-08-28 05:00:04

事件

显然,一个被禁用的<input>没有被任何事件处理

有没有办法解决这个问题?

<input type="text" disabled="disabled" name="test" value="test" />
$(':input').click(function () {
    $(this).removeAttr('disabled');
})

在这里,我需要单击输入来启用它。但是如果我不激活它,输入就不会被发布。


当前回答

今天我们遇到了类似的问题,但我们不想更改HTML。我们使用mouseenter事件来实现

var doThingsOnClick = function() {
    // your click function here
};

$(document).on({
    'mouseenter': function () {
        $(this).removeAttr('disabled').bind('click', doThingsOnClick);
    },
    'mouseleave': function () {
        $(this).unbind('click', doThingsOnClick).attr('disabled', 'disabled');
    },
}, 'input.disabled');

其他回答

您可以考虑使用readonly而不是disabled。使用一些额外的CSS,您可以对输入设置样式,使其看起来像一个禁用字段。

实际上还有另一个问题。事件更改仅在元素失去焦点时触发,考虑到禁用字段,这不是逻辑。可能您正在将数据从另一个调用推入该字段。要做到这一点,你可以使用事件'bind'。

$('form').bind('change', 'input', function () {
    console.log('Do your thing.');
});

今天我们遇到了类似的问题,但我们不想更改HTML。我们使用mouseenter事件来实现

var doThingsOnClick = function() {
    // your click function here
};

$(document).on({
    'mouseenter': function () {
        $(this).removeAttr('disabled').bind('click', doThingsOnClick);
    },
    'mouseleave': function () {
        $(this).unbind('click', doThingsOnClick).attr('disabled', 'disabled');
    },
}, 'input.disabled');

$(函数(){ $(“输入:禁用”).closest (" div ") .click(函数(){ (美元);(输入:禁用)。attr(“禁用”,假).focus (); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js " > < /脚本> < div > <input type="text" disabled /> < / div >

我会建议一个替代方案-使用CSS:

input.disabled {
    user-select : none;
    -moz-user-select : none;
    -webkit-user-select : none;
    color: gray;
    cursor: pointer;
}

而不是disabled属性。然后,您可以添加自己的CSS属性来模拟禁用的输入,但是具有更多的控制。

也许你可以将字段设置为只读,并在提交时禁用所有只读字段

$(".myform").submit(function(e) {
  $("input[readonly]").prop("disabled", true);
});

而输入(+脚本)应该是

<input type="text" readonly="readonly" name="test" value="test" />
$('input[readonly]').click(function () {
  $(this).removeAttr('readonly');
});

一个活生生的例子:

$(".myform").submit(function(e) { $("input[readonly]").prop("disabled", true); e.preventDefault(); }); $('.reset').click(function () { $("input[readonly]").prop("disabled", false); }) $('input[readonly]').click(function () { $(this).removeAttr('readonly'); }) input[readonly] { color: gray; border-color: currentColor; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="myform"> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <input readonly="readonly" value="test" /> <button>Submit</button> <button class="reset" type="button">Reset</button> </form>