简体   繁体   中英

Can't unbind click from nested <li>

I have a function that allows me to expand and collapse an unordered list by clicking on the list item, but the problem is in the lowest level LI I have a table with a checkbox embedded, and when the user clicks on the table [edit] the background image of the parent li is shown.

The way I see it there are two main routes to solve this, somehow just remove the background image for just the child li or to unbind the click event for the child li. I am trying to unbind the click handler on the lowest level LI, but it just won't work. Below is a simplified version. A user shouldn't be able to click on the td cells.

If you view the jsfiddle I can't add the png files that will completely replicate the problem to where you can see the issue, but as long as the 'alert' triggers on the child li you can tell the child li is still clickable.

http://jsfiddle.net/3CgQ6/9/

HTML

<ul id="expList">
  <li>Category 1
     <ul>
        <li class="detailLI"> Category 1.1
           <table>
             <tr><td><input type="checkbox"></td><td>Part A</td></tr>
             <tr><td><input type="checkbox"></td><td>Part B</td></tr>
             <tr><td><input type="checkbox"></td><td>Part C</td></tr>
           </table>
        </li>
        <li class="detailLI"> Category 1.2
           <table>
             <tr><td><input type="checkbox"></td><td>Part D</td></tr>
             <tr><td><input type="checkbox"></td><td>Part E</td></tr>
           </table>
        </li>
     </ul>
  </li>
</ul>

JavaScript

    $('#expList').find('li:has(ul)')    
        .click( function(event) {
            //If line item is expandable but has no line items then call the service to retrieve data
            if($(event.target).hasClass('collapsed') && $(event.target).find('li').length==0){                  
                retrieveResults($(event.target));
            }
            //Toggle the lists if they show or not
            $(event.target).toggleClass('expanded');
            $(event.target).children('ul').slideToggle('medium');
            event.stopPropagation();
            $('.detailLI').unbind("click");
        })
        .addClass('collapsed')
            .removeClass('expanded')
            .children('ul').hide();

Use on() and off() to bind/unbind events. All other methods of binding/unbinding have been deprecated as of jQuery 1.7.

为什么不将click事件添加到复选框元素,然后将“ event.stopPropagation”放在此处以停止冒泡呢?

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