最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting a native js event object to jQuery event object - Stack Overflow

programmeradmin4浏览0评论

I want to convert a native JavaScript event object to jQuery event object.

Actually this is the problem:
I have bound an event handler to documents keyup event via jQuery and there are some text boxes on the page with which a keyup event handler is bound via inline JavaScript.

The problem is when the text box's event handler is fired the document's event handler also gets fired because the event "bubbles up" I can modify the event handler function bound by inline JavaScript but not that line itself.

What I am looking for is a cross browser, a way to cancel the event bubbling that's why I wanted to convert it to a jQuery object.

I want to convert a native JavaScript event object to jQuery event object.

Actually this is the problem:
I have bound an event handler to documents keyup event via jQuery and there are some text boxes on the page with which a keyup event handler is bound via inline JavaScript.

The problem is when the text box's event handler is fired the document's event handler also gets fired because the event "bubbles up" I can modify the event handler function bound by inline JavaScript but not that line itself.

What I am looking for is a cross browser, a way to cancel the event bubbling that's why I wanted to convert it to a jQuery object.

Share Improve this question edited Sep 20, 2022 at 21:46 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 19, 2010 at 11:08 ShaheerShaheer 2,1474 gold badges25 silver badges39 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

Looking to the code of jQuery (I looked at 1.7, but I think it is available before that as well) it is easy to create a jQuery Event from a native event using:

var jQueryEvent = jQuery.Event(event);

If all you want to do is prevent an event from bubbling, that's easy without jQuery. Don't be scared of stepping outside the world of jQuery. It's not as plicated as some people would have you believe.

function stopEventPropagation(evt) {
    if (typeof evt.stopPropagation != "undefined") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
}

// Example
document.getElementById("yourInputId").onkeyup = function(evt) {
    evt = evt || window.event;
    stopEventPropagation(evt);
};

You can remove onclick or whatever inline eventhandler attributes with jQuery right after page load eg.:

$(document).ready(function () {

  $('#someInput').removeAttr('onclick');

});

Then attach Your event handlers to customize behaviour.

发布评论

评论列表(0)

  1. 暂无评论