开发者

Checkbox not checking in a jQuery slideToggle UL list

I'm using some simple jQuery to be able to slideToggle a series of nested < ul > This is working fine, however, if I have checkboxes in my < li > elements, the cannot be checked

I have the following jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        $('.toggle li:has(ul)').click(function (event) {
            $(this).css('list-style-type', $(this).children().is(':hidden') ? 'circle' : 'square')
            $(this).children().slideToggle('fast')
            return false
        })

        .css({ cursor: 'pointer', 'list-style-type': 'circle' })
        //show to start with
        .children().show()

  开发者_开发知识库      $('li:not(:has(ul))').click(function (event) { return false })
    })
</script>

This is applied to my HTML:

<h1>
    Toggle</h1>
<ul class="toggle">
    <li><a href="#">Item 1</a></li>
    <li>Item 2
        <ul>
            <li><a href="#">Item 2.1</a></li>
            <li><a href="#">Item 2.2</a></li>
        </ul>
    </li>
</ul>
<ul class="toggle checkboxes">
    <li><a href="#">Item 1</a></li>
    <li>Item 2
        <ul>
            <li>
                <input type="checkbox" name="chk1" /><label for="chk1">Red (86)</label></li>
            <li>
                <input type="checkbox" name="chk2" /><label for="chk2">Yellow (86)</label></li>
            <li>
                <input type="checkbox" name="chk3" /><label for="chk3">Green (173)</label></li>
        </ul>
    </li>
</ul>

Both lists slide as expected, however, the checkboxes in the second list do not check.. nothing happens.

I think it is something to do with my click event in my jQuery, but I'm not sure how to fix it.

I'm using some CSS (pretty sure this isn't the cause of it) The css mainly prevents icons / style-types being shown on the list containing checkboxes.

<style type="text/css">
    ul { list-style-type: circle; margin-left: 10px; margin-top: 10px; }
    .checkboxes ul { margin-left: 0px; list-style-type: none; }
    ul a { font-weight: normal; text-decoration: none; }
    ul a:hover { text-decoration: underline; }
</style>

If there are better ways of doing this, I'm all ears


Change

 $('li:not(:has(ul))').click(function (event) { return false }) 

to

 $('li:not(:has(ul))').click(function (event) { 
  event.stopPropagation();
 }) ;

Check this article on why should you stop using return false in the vent handlers.

http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

An excerpt from the article:

What return false is really doing First off, return false is actually doing three very separate things when you call it:

1.event.preventDefault();
2.event.stopPropagation();
3.Stops callback execution and returns immediately when called.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜