在该字段的焦点上更改只读属性

时间:2019-02-02 11:27:22

标签: javascript html

我有一个类型为=“ password”的字段。由于某些原因,我将该字段设置为只读。想法是onfocus-我将删除readonly属性。

当前,当我执行以下操作时,我会收到警报

<input type="password" id="pt" onclick="function hi()
{alert ('hi')}; hi()" readonly>

但是下面的onclick代码不起作用:

  onclick="function hi(){$(this).removeAttr('readonly');};hi()"

有什么建议吗?

4 个答案:

答案 0 :(得分:3)

尽管我不理解readonly的必要性,但最终您将要编辑该输入的数据时,但是如果您要进行编辑,则可以使用以下方法

使用Jquery

<input type="password" id="pt" onclick="$(this).removeAttr('readonly');" readonly>


使用香草JS

<input type="password" id="pt" onclick="this.removeAttribute('readonly')" readonly>

input[readonly] {
  background: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" id="pt" onclick="$(this).removeAttr('readonly');" readonly>

<br><br>

<input type="password" id="pt" onclick="this.removeAttribute('readonly')" readonly>

答案 1 :(得分:0)

通过javascript附加点击侦听器:

document.getElementById('pt').addEventListener('click',function(){
  this.removeAttribute('readonly');
});

但是最好使用焦点和模糊事件:

document.getElementById('pt').addEventListener('focus',function(){
      this.removeAttribute('readonly');
    });
document.getElementById('pt').addEventListener('blur',function(){
      this.setAttribute('readonly','');
});

答案 2 :(得分:0)

这应该有效:

<input type="password" id="pt" onclick="$('#pt').attr('readonly', false);" readonly>

答案 3 :(得分:0)

出于可读性考虑,我建议将其移至单独的函数中

<input type="password" id="pt" onclick="hi()" readonly>
function hi() {
    $(this).prop('readonly', false);
}
相关问题