tags:

views:

75

answers:

2
var func = function()
{
    $(this).hide();
    $parent = $(this).parent();
    $parent.removeClass('my_signature_mouseover');
    var text = $(this).val();
    var $span = $("#status span");
    $span.text(text);
    $span.show();
};
$("#status input").keyup(function (e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
       func();
    }
}).blur(func);

I want to make func run if blur or pressing "Enter" on it. But the above code works only when blur, in the case of pressing "Enter",it reports "Permission denied to access parentNode".

Although I know it's something related with this keyword in different context,I've no idea how to fix it.

A: 

Try this:

var func = function(elem)
{
    elem.hide();
    var $parent = elem.parent();
    $parent.removeClass('my_signature_mouseover');
    var text = elem.val();
    var $span = $("#status span");
    $span.text(text);
    $span.show();
};
$("#status input").keyup(function (e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
       func($(this));
    }
}).blur(function () {
    func($(this));
});
RaYell
+1  A: 

You are calling the func, with a normal function call, that causes inside func, the this variable will refer to the global object (window).

You have to execute the function with call, in order to preserve the context (the 'this' value), which is the element that triggered the event:

$("#status input").keyup(function (e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
       e.preventDefault(); // stop event propagation
       func.call(this);
    }
}).blur(func);
CMS
It's near.But I've called $(this).select() first,and after pressing "Enter",the value of input is cleared,how to prevent that from happening?
Shore
you might want to cancel the propagation of the keyup event... edited...
CMS
Not working,I guess the keyup function get called after the default behaviour.
Shore
I need more details, could you post a detailed example on http://jsbin.com exposing the wrong behavior that you are experiencing?
CMS
Oh,it's caused by typo..
Shore