javascript: Possible to add event handler that runs after the default behavior?

馋奶兔 提交于 2019-12-24 00:16:22

问题


I have an event handler that I would like to have executed after the default javascript handling of that event occurs.

Is this possible?

EDIT: For example: everytime a keypress event is fired, i'm logging event information about that keypress(similar to console.log). Now, when I press backspace and view the fields contents via the event handler, the value of the text field produces the value without the backspace since the event handler grabs the contents of the field before the actual removal of the last letter.

I would like, in this case, for the default backspace event to occur and then have my event handler fired upon completion.

Thanks!


回答1:


I believe your problem is caused by listening for the keypress event instead of the keyup event. Basically this means that you are getting the value of the textarea before the character is put in the dom.

Try changing your keypress handler to a keyup handler.

An example would be:

$('input, textarea').keyup(function(ev) {

    console.log( $(this).val() );

});

Edit: Found this question which appears to be your exact problem.




回答2:


I see that there was a different issue other than what is named in the question. In that regards, +1 Sam :).

However, I would like to address the question here, and not just the offshoot. There is a way to handle specific keypress events or default to one.

keypress bubbles. So use a global one, and then for anywhere you need it locally, use e.stopPropagation() in order to stop it from bubbling. Here is a demo of it working: http://jsfiddle.net/2EwhR/

here is the html:

<div id="d1">_</div>
<br><hr>
<div id="d2"><input id="i1" type="text" /></div>

js:

var d1 = document.getElementById("d1");
window.onkeypress = function(ev){
 d1.innerHTML = "keyCode: " + ev.keyCode;
};
var d2 = document.getElementById("d2");
var i1 = document.getElementById("i1");
d2.onkeypress = function(ev){
  d1.innerHTML = "blocked";
  ev.stopPropagation();
};



回答3:


This would be a way to run custom code after the event has bubbled up to the browser, i.e. the typed in value would first be added to the text field, then a second later your custom function would run. You could make this a much smaller amount of time if you wish.

$("input").on("keypress", function () {
  setTimeout(function () {
    alert("new value should have been already added to text field. Now we are executing some custom stuff");
  }, 1000);
  return true;
});

working demo



来源:https://stackoverflow.com/questions/14187585/javascript-possible-to-add-event-handler-that-runs-after-the-default-behavior

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