开发者

Jquery registering a click on an element that was not clicked strange behavior

开发者 https://www.devze.com 2023-04-05 03:55 出处:网络
Given the following html: <table> <tr> <td> <img rel=\"20110914103319-9589184176\" src=\"images/redXblackBackground.png\" style=\"float: left;\">

Given the following html:

<table>
    <tr>
        <td>
            <img rel="20110914103319-9589184176" src="images/redXblackBackground.png" style="float: left;">
        </td>
    </tr>
</table>

I have the following code to register an even when the row is clicked.

$('tr').live('click',function(e){
    var tagType = $(this).get(0).tagName;
    console.log(tagType);
});

And I have the following code to tell when the image is click on.

$("td img").live开发者_如何学编程('click',function(e){
    opId = $(this).attr('rel');
    console.log(opId);
});

The issue is that when I click on the image, it registers that I click on the tr element. I thought perhaps it had to do with the order that the two click block of code were ordered but it made no difference. I am failing to see why the click on the image would register a click on the tr element and not on the img element.


This happens because the event propagates up the DOM tree, triggering your other event. Stop it from propagating and your code should work:

$("td img").live('click',function(e){
    opId = $(this).attr('rel');
    console.log(opId);

    e.stopPropagation();
});


Edit: My answer used the .click jquery function whereas your question used .live so maybe my answer isn't as relevant as Blender's.


Because the img tag is inside the tr tags it is falling through to the click function on its parent tr.

The only way around this that I have ever used is to return false; after all of your required javascript has been completed.

For example:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('tr').click(function() {
            alert('tr');
        });

        $('tr span').click(function() {
            alert('span');
            return false;
        });
    });
</script>
<table width="100%">
    <tr style="background: #ccc;">
        <td>
            <span id="test">Test</span>
        </td>
    </tr>
</table>

Perhaps there is a better way around this but that is how I do it because I don't usually need click events to return a true of false value anyway.

0

精彩评论

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