大家好~~  我就直接了当的说了,我的页面中有如下内容:
 
 <div id="tree">
        <ul>
            <li id="root1">
                root
                <ul>
                    <li id="first1">first1
                        <ul>
                            <li id="second1">second1</li>
                            <li id="second2">second2</li>
                        </ul>
                    </li>
                    <li id="first2">first2</li>
                    <li id="first3">first3</li>
                </ul>
            </li>
            <li id="root2">
                root2
            </li>
             <li id="root3">
                root3
            </li>
        </ul>
    </div>
我写了个jquery方法 想点击一个li的时候弹出id,这个li必须是包含ul的li 也就是说要包含子元素才行
(function($) {
    $.fn.tree = function() {
        var content = $(this).html();
        $(this).find("li").each(function() {
            if($(this).children("ul").length>0){
                $(this).bind("click", function(evnet) {
                        alert(this.id);
                      evnet.stopPropagation();
                });
            }
        });    };
})(jQuery)
但为什么每次点击id是second1、second2、first2或者first3的时候也会弹出来呢? 怎么改呢?

解决方案 »

  1.   

    思路:
    1.为这类li添加响应事件
    2.在点击事件中判断被点击的li是否含有ul的子元素,如果有就显示id
      

  2.   

    你应该$("ul>li")给才对
    给你个例子、你自己研究吧!!!
    --------------
    <form>
      <label>Name:</label>
      <input name="name" />
      <fieldset>
          <label>Newsletter:</label>
          <input name="newsletter" />
     </fieldset>
    </form>
    <input name="none" /> 
    --------------------js :$("form > input") 
    ------------------
    结果:[ <input name="name" /> ] 
      

  3.   

    (function($) {
      $.fn.tree = function() {
      var content = $(this).html();
      $(this).find("li").each(function() {
      if($(this).children("ul").length>0){  $(this).bind("click", function(evnet) {
      alert(this.id);
      evnet.stopPropagation();
      });
      }
      });将这行代码前,alert($(this).children("ul").length);
    你会有所发现!
      };
    })(jQuery)
      

  4.   

    这样就行了。
    <script type="text/javascript">
    $(document).ready(function(){
      $("li").click(function(e){
        if($(this).children("ul").length>0){
    alert($(this).attr("id"));
    }
    e.stopPropagation();
      });
    });
    </script>
      

  5.   

    把click事件定义在li的文字上,不要定义在整个li上