在编辑输入 jQuery 后激活只读返回

activate readonly back after editing the input jquery

本文关键字:激活 只读 返回 jQuery 编辑 输入      更新时间:2023-09-26
完成

输入编辑后如何激活只读返回?

这是我现在的代码:

<script type="text/javascript">
$(document).ready(function () {
         $("input").bind('click focus', function(){
                $('input').each(function(){
                        $(this).attr("readonly", false);
                        });
                });
         });
</script>

像这样的输入:

<input type="text"  class="m" readonly="readonly" id="anchor_text">

我认为 Focusout 有些东西,当我转到下一个输入时,我需要将只读放回去,因此除非我再次点击它,否则无法更改编辑的输入。

尝试:

$("input").bind('click focus', function(){
     $(this).attr("readonly", false);
  }).bind('blur', function(){
     $(this).attr("readonly", true);
 });​

演示 : http://jsfiddle.net/DkCvu/1/

对不起,但我很难看到这一点的意义。如果我做对了,您希望输入字段在被用户单击或选择之前不可编辑(这基本上就是输入字段的工作方式:除非您选择它们,否则您无法更改它们的值)。在这些输入字段失去焦点后,它们应恢复为只读。
如果是这种情况,你就把事情复杂化了。但是,这不关我的事。完成IMO的最佳方法是委派事件。

因此,我在纯JS和jQuery上整理了几个小提琴。两者都远非完美,但应该可以帮助您。

常规JS(在这里小提琴):

var dv = document.getElementById('inputDiv');
if (!dv.addEventListener)
{
    dv.attachEvent('onfocusin',switchRO);
    dv.attachEvent('onfocusout',switchRO);
}
else
{
    dv.addEventListener('focus',switchRO,true);
    dv.addEventListener('blur',switchRO,true);
}
function switchRO (e)
{
    var self;
    e = e || window.event;
    self = e.target || e.srcElement;
    if (self.tagName.toLowerCase() === 'input')
    {
        switch (e.type)
        {
            case 'onfocusin':
            case 'focus':
                self.removeAttribute('readonly');
            break;
            default:
                self.setAttribute('readonly','readonly');
        }
    }
    return true;
}

在jQuery中,这可能看起来像这样(jQuery与.on,jsfiddle在这里):

$('#inputDiv input').on(
    {
        focus: function()
        {
            $(this).removeAttr('readonly');
        },
        blur: function()
        {
            $(this).attr('readonly','readonly');
        }
    });

我发布了jQuery和纯JS,因为我发现了解jQuery屏幕后面发生的事情既有信息又有教育意义。