简体   繁体   中英

div click under anchor tag not working jquery

JS FIDDLE DEMO

Here a child div inside anchor tag, how to get click event of child div, for example if user click on div having class .press_me alert msg get display , and if user click anywhere on main div it should redirect to respective anchor link

HTML :

<a href="https://www.google.co.in"><div class="dv_child"> America <div class="press_me">click me</div></div></a>
 <a href="https://www.google.co.in" target="_blank"><div class="dv_child"> India <div class="press_me">click me</div></div></a>
<a href="https://www.google.co.in" target="_blank"><div class="dv_child"> Russia <div class="press_me">click me</div></div></a>
<a href="https://www.google.co.in" target="_blank"><div class="dv_child"> Germany <div class="press_me">click me</div></div></a>

JQUERY:

$(".press_me").on('click', function () {
    alert($(this).parent().html());
});

USe $(this) instead of $this . Also you can use event.stopPropagation() to stop propagating the child click to parent.

In your case you just need to prevent the default behaviour of anchor tag. For that, use event.preventDefault()

$(".press_me").on('click', function (e) {
    e.preventDefault()
    alert($(this).parent().html());
});

Updated fiddle

Use event.preventDefault it stops the default action

$(".press_me").on('click', function (event) {
     event.preventDefault();
    alert($(this).parent().html());
});

Fiddle

Also you will have to update first element anchor:

HTML

<a href="https://www.google.co.in" target="_blank"><div class="dv_child_1"> America <div class="press_me">click me</div></div></a>

<a href="https://www.google.co.in" target="_blank"><div class="dv_child_1"> India <div class="press_me">click me</div></div></a>

<a href="https://www.google.co.in" target="_blank"><div class="dv_child_1"> Russia <div class="press_me">click me</div></div></a>

<a href="https://www.google.co.in" target="_blank"><div class="dv_child_1"> Germany <div class="press_me">click me</div></div></a>

JS (Same as already suggested)

$(".press_me").on('click', function (event) {
    event.preventDefault();
    alert($(this).parent().html());
});

JSFIDDLE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM