我有一个带有事件集的元素,例如
<input type="text" id="txt" onkeyup="javascript: alert('keyup');" />现在,我想截获这个事件,并运行默认脚本之外的其他一些脚本。我写了以下代码:
jQuery(document).ready(function(){
var old = $("#txt").keyup;
$("#txt")
.unbind('keyup')
.attr('onkeyup', '')
.each(function() { this.onkeyup = null; });
$("#txt").keyup(function(event){
alert("before old call");
//old.call($(this));
alert("after old call");
});
});但它并没有像我预期的那样工作。有人知道怎么做吗?
链接到fiddle:http://jsfiddle.net/p5JeA/
如果输入的keyup事件不是内联的,而是使用jQuery绑定设置的,该怎么办?我想要覆盖/扩展默认行为,我不想更改基本代码。
发布于 2011-08-12 02:24:14
这里有一个有效的工具:http://jsfiddle.net/mrchief/p5JeA/2/
var old = $("#txt")[0].onkeyup;
$("#txt")[0].onkeyup = null; // or function () {};
// or $("#txt").removeAttr('onkeyup');jQuery未包含在资源中。另外,我注释掉了一些你不需要的部分。
发布于 2011-08-12 02:31:25
我已经把你的小提琴叉到这里了:http://jsfiddle.net/xdaTH/
我启用了jQuery而不是MooTools,但也使用了.get(0)来获取实际的dom元素,该元素定义了一个onkeyup函数。
脚本:
jQuery(document).ready(function() {
var old = $("#txt").get(0).onkeyup;
$("#txt").unbind('keyup').attr('onkeyup', '').each(function() {
this.onkeyup = null;
});
$("#txt").keyup(function(event) {
alert("before old call");
old.call(this);
alert("after old call");
});
});发布于 2011-08-12 02:31:24
创建自己的自定义事件,然后触发它:
$('#txt').bind('custom', function(event) {
alert("before old call");
//old.call($(this));
alert("after old call");
});
$('#txt').trigger('custom', ['Custom', 'Event']);你可以在这里找到相关信息:jquery trigger
https://stackoverflow.com/questions/7030872
复制相似问题