Pregunta

Given a document such as this:

<body><div class="a"><div class="b"><div class="c"></div></div></div></body>

(in the example everything is a div - but they could be anything)

I want to run a click event handler for the div which was clicked and all its parent's

i.e. if you click on .c I would expect the event to fire for .c then .b then .a If you click on .b then the event should fire for .b then .a

N.B. in this instance I am using $('body').on('click', function(event){...}) using $('div').click(function(event){...}) is not a practical option in my instance for reasons not relevant to the question.

I tried walking the dom tree from within the event handler which works but the event object contains the wrong offsets.

So my question really is - is there a built in way to have the event handler called with the above pattern.

Or failing that - is there a built in way to manipulate offsets the event object given a "from" and "to" element. i.e. something like AdjustOffsets(event, $target, $target.parent())

Or failing that - what logic do I need in order to perform this manipulation by hand.

On the last case I have this code but it doesn't work.

if ($target.css('position') != 'static' && $target.css('position') != '')
    {
        event.clientX += $target.css('left');
        event.clientY += $target.css('top');
    }
    event.clientX += $target.css('borderLeftWidth');
    event.clientY += $target.css('borderTopWidth');
    event.clientX += $target.css('marginLeft');
    event.clientY += $target.css('marginTop');
    $target = $target.parent();
    event.clientX += $target.css('paddingLeft');
    event.clientY += $target.css('paddingTop');

This fails because the CSS properties contain units. The units are easily stripped but I believe some browsers return the original unit here (which could be em or pt for example) whereas the clientX property is required to be pixels - so conversion is necessary.

Also it was a best-guess on my part and probably misses a thousand obscure css3 cases - hence my ambitious desire for some kind of built-in method.

¿Fue útil?

Solución

I'm not quite sure what your question is. Do you want a click-event to trigger on for instance div.a when you click on div.c? If so. This should already happen, since click events by default bubble through the DOM.

Check out this fiddle and you'll see that if you'd click on div.c, the click events for div.b and div.a will be fired as well.

edit: New fiddle, with just 1 on()

Otros consejos

You could try a recursive trigger within your event handler, like this:

$(document).on('click', '.someClass', function(e){

    // .. do stuff

    $(this).parent('.someClass').trigger('click');
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top