当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Problem with event handler

问题描述:

function getFieldName(e) {

e = e || window.event;

var key = e.keyCode || e.which,

target = e.target || e.srcElement;

alert(target.name);

return (key != 13);

}

I have the above function called on body tag onkeypress = getFieldName(event);

I get the name of desired field but not able to check in IE as well as FF

if(target.name == 'check') {

// works fine in FF but in IE I'm not able

// to come inside this if-block, please suggest

}

thanks

网友答案:

I see you've tagged this post as jQuery... If you actually use jQuery to manage the event handler then you can use e.which to find the key that was pressed and e.target to find the DOM target. It also worries about the cross-browser stuff for you.

To attach a function as an event handler, you can follow this simple example: $(document).keypress(getFieldName);

网友答案:

jQuery already normalizes some event properties internally, so you can just use event.target and event.which, you don't need to check for others, like this:

$(document).keypress(getFieldName);
function getFieldName(e) {
    alert(e.target.name);
    if(e.which == 13) {
      alert("Key pressed was enter");  
    } else {
      alert("Key pressed was not enter");  
    }
}
​

You can view a quick demo here

分享给朋友:
您可能感兴趣的文章:
随机阅读: