0

用户在 div 中按下一个键后,html 被设置为“”。但是,在用户离开 div 后,我想将 html 设置回原来的值。我怎样才能做到这一点?

到目前为止,我有以下代码:

$(document).one('keypress',"#id",function() { 
        $(this).html("");
    }).focusout(function(){
        //do something 
    });
4

4 回答 4

6

使用以下方法将其缓存在元素本身中.data()

$(document).one('keypress',"#id",function() { 
    $(this).data('html',$(this).html()).html('');
}).focusout(function(){
    $(this).html($(this).data('html'));
});

我更喜欢这种方法,因为通过将数据存储在 上this,它可以与任何选择器一起使用,包括匹配多个 DOM 元素的选择器。您只需要确保页面上的任何其他代码都没有使用data()变量(此处)。'html'

于 2013-01-21T18:13:22.247 回答
3

怎么样:

(function()
{
    var html = null;
    $(document).one('keypress',"#id",function() { 
        html = $(this).html();
        $(this).html("");
    }).focusout(function(){
        //do something 
        $(this).html(html);
    });
})();

我已经将它包装在一个自我执行的匿名函数中,这样你就可以将html变量保持在主范围之外。

或者以更 jQuery 的方式:

$(document).one('keypress',"#id",function() { 
    $(this).data('orightml', $(this).html());
    $(this).html("");
}).focusout(function(){
    //do something 
    $(this).html($(this).data('orightml'));
});

通过这种方式,我们将原始 html 存储在元素上。

于 2013-01-21T18:14:48.373 回答
2

也许是这样的:

var orig;
$(document).one('keypress',"#id",function() { 
        orig = $(this).html();
        $(this).html("");
    }).focusout(function(){
        //do something 
        $(this).html(orig);
    });
于 2013-01-21T18:13:06.043 回答
0

您需要将值存储在一个变量中,以便在焦点消失后恢复它。

var divValue;
$(document).one('keypress',"#id",function() { 
    divValue = $(this).html();
    $(this).html("");
}).focusout(function(){
    $(this).html(divValue);
});
于 2013-01-21T18:14:01.790 回答