开发者

Determine the elements which an event has bubbled through

开发者 https://www.devze.com 2023-02-19 06:11 出处:网络
Given a simplified document like this: <div id=\"outerDiv\"> <div id=\"innerDiv\"> <input id=\"theInput\" />

Given a simplified document like this:

<div id="outerDiv">
    <div id="innerDiv">
        <input id="theInput" />
    </div>
</div>

If I were to click on #theInput, 开发者_运维知识库the click event would bubble up to #innerDiv and then #outerDiv. What I'd like to do would be to put a handler on #outerDiv to listen for those clicks, and then inspect the 'bubble-chain' to see which elements have previously received this same click event.

So, for example, clicking on #theInput the handler in #outerDiv would give me [#outerDiv, #innerDiv, #theInput]. If I were to click outside of #theInput, but still inside #innerDiv then the result would be [#outerDiv, #innerDiv]

Just to clarify, the actual document is not as simple as this, and there could be any number of children or siblings at each level. Also, when I refer to #theInput, I'm referring to the element itself, that is, I'm not looking for an array of IDs. Lastly, given that there could be any number of elements, I'd like to avoid adding extra handlers to intermediate elements.

jQuery is welcome in my house.


Seems like:

function myHandler(ev) {
  var $bubbleParents = $(ev.target).parents();

  // ...
}

is all you need, esp. if you're using jQuery and your event handlers will have this bound to the element relevant to the handler code. The list of parents from the target will tell you all the elements that the event can possibly bubble to, and your this reference will be one of the elements in that list. (I think the list of parents is in "inner-to-outer" order, but I'd have to check in a fiddle.) Thus you can tell which elements have already been "visited" and which haven't.


With the event object, use the target to find out the click element. From there you can use the parents() function in jQuery to find all the parents in the chain.

var parents;
handler = function(e){
 // specifying the limit node in parents
 parents = $(e.target).parents("#outerDiv");
};


$('outerDiv').bind('click', function(e) {
    var current = e.target;
    var arrayClicked = new Array();
    arrayClicked[] = current;
    function test() {
        if(current.parent() == $('.outerDiv')) {
            return arrayClicked;
        } else {
            arrayClicked[] = current;
            current = current.parent();
            test();
        }
    }
    var yourdivs = test();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消