无法在IE中的输入字段上设置只读

szp*_*pic 4 javascript jquery internet-explorer google-chrome

我有一个简单的输入字段:

<input id="myInput" class="someClass"></input>
Run Code Online (Sandbox Code Playgroud)

和一些JQuery代码:

$(e.currentTarget).prop('readonly', true);
Run Code Online (Sandbox Code Playgroud)

这里e.currentTarget[object HTMLInputElement]作为IE11的名字吧。

我只是试图将此输入字段设置为只读。在chrome中,该代码有效,但在IE中则无效。我已经尝试过了:

.prop('readonly','readonly');
.prop('readonly', '');
.attr('readonly', true);
Run Code Online (Sandbox Code Playgroud)

但它们都无法在IE11中工作(在Chrome中,每个人都可以工作)

T.J*_*der 5

好的,这很奇怪:如果您将字段设为焦点时将其设置为只读,则IE11似乎有点笨拙,其中一种笨拙的方法是让您在光标在那里时继续修改字段- 一些击键,但其他击键。这是一个例子:小提琴

$("#myInput").one("click", function(e) {
    $(e.currentTarget).prop('readonly', true);
    display("e.currentTarget.readOnly: " + e.currentTarget.readOnly);
});
$("#myInput").on("keydown", function(e) {
    display("e.currentTarget.readOnly: " + e.currentTarget.readOnly);
});
function display(msg) {
    $("<p>").html(String(msg)).appendTo(document.body);
}
Run Code Online (Sandbox Code Playgroud)

设置之前添加此行readOnly可修复此问题(fiddle):

$(e.currentTarget).blur();
Run Code Online (Sandbox Code Playgroud)

旁注:您不需要jQuery来设置readOnly属性,只需:

e.currentTarget.readOnly = true; // Note the capital O
Run Code Online (Sandbox Code Playgroud)