e.keyCode does not work

不羁的心 提交于 2019-12-02 09:25:14

问题


I would like to ask you about something that does not work for me ? If you could help me please.

Html:

<input type='text' class='blabla' onkeyup="function(id, e);">

Javascript Code:

function(id, e) {
  var comment = $(".blabla").val();`<br />
  // alert(message);  WORK
   alert(e.keyCode) 
 // DOES NOT WORK
}

回答1:


With minimum modifications ,

<input type='text' class='blabla' onkeyup="doSomething(e)">

function doSomething(e){
var comment = $(".blabla").val();
var id = this.id;
alert(e.keyCode) // Now it should work
}

The first parameter in the doSomething function will be the event object. The this variable will return a reference to the input element.

If you modify your posted js and provide a name to the function as I have done without making changes to the function parameters, you will find that id will contain the event object.




回答2:


First give function a name .Lets say function keyfinder .Then call it on keyup as onkeyup="function keyfinder(id, event);"

Then try the following:

function keyfinder(id, e){
var eventval = e || window.event;
var comment = $(".blabla").val();
// alert(message); WORK
alert(eventval.keyCode);

}




回答3:


Function can't be a function name. In your HTML, change function(id, e) into, say, inputKeypress(id, e), or any other name you see fit.

In your JavaScript, declare he function like so:

function inputKeypress(id, e) {
    do stuff
}



回答4:


you need to give some other name than function to a function

use this.id intead of just id

your php file:

<input type='text' class='blabla' onkeyup="funkeyup(this.id, e);">



回答5:


You're obviously using jQuery, so you could define the keyup event in your script as well:

HTML/PHP

<input type="text" class="blabla" id="mySuperUniqueId" />

JavaScript

$(".blabla").keyup(function(e) {
  console.log("pressed key with code", e.keyCode, "on id", this.id);
});

The anonymous function passed as a handler in $(...).keyup(handler) receives the jQuery Event you're looking for. Within that function this is set to the DOM Element the event is attached to, in this case the input field. If you intend to work on that field, like using .val() you'd have to wrap it in the $(...) first:

$(".blabla").keyup(function(e) {
  var $input = $(this)
  console.log("current value is", $input.val());
});

Just keep in mind, that the value might not have changed, when you're using keydown instead of keyup.

For more infos on that, take a look at the jQuery-API




回答6:


You can't use function as function name in onkeyup event.



来源:https://stackoverflow.com/questions/21204295/e-keycode-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!