为div添加click事件

时间:2013-03-31 06:37:09

标签: javascript jquery html

美好的一天,我想通过BIND方法将click方法附加到div。 我的附加代码是

$("#brend_list > #mCSB_1 > .mCSB_container > div > a").bind('click',function(){
id=$(this).attr('id');
ttl=$(this).parent().children("span").html();
state=$(this).hasClass("checked");

if(state) {$(this).removeClass("checked");
$("#"+id+"_filter").remove();
}
else{$(this).addClass("checked");


$("#filters").append(" <div style='display:inline-block;' id='"+id+"_filter' class='filter_brands' onclick='brend_uncheck(\""+id+"\"); $(this).remove();'><span>"+ttl+"</span><b>x</b></div> ");


}});

我的div结构是

<div id="brend_list" class="mCustomScrollbar _mCS_1">
  <div class="mCustomScrollBox mCS-light" id="mCSB_1" style="position:relative; height:100%; overflow:hidden; max-width:100%;">
   <div class="mCSB_container" style="position: relative; top: 0px;">
    <div><a id="filt_brend001"></a><span>Loreal Paris</span></div><!-- this <a> -->
    <div><a id="filt_brend002"></a><span>Laura Mercier</span></div>
    ...........
    </div>
    <div class="mCSB_scrollTools" style="position: absolute; display: block;">
      <div class="mCSB_draggerContainer"><div class="mCSB_dragger" style="position: absolute; height: 110px; top: 0px;" oncontextmenu="return false;">
        <div class="mCSB_dragger_bar" style="position: relative; line-height: 110px;">  
        </div>
      </div>
      <div class="mCSB_draggerRail">
      </div>
     </div>
    </div>
   </div>
</div>

但它没有附加。

1 个答案:

答案 0 :(得分:2)

您应该更改

$("#brend_list > #mCSB_1 > .mCSB_container > div > a")

$("#brend_list > #mCSB_1 > .mCSB_container > div > a + span")

上面的小提琴是here

或,从

更改HTML
<div><a id="filt_brend001"></a><span>Loreal Paris</span></div>

<div><a id="filt_brend001"><span>Loreal Paris</span></a></div>

上面提到的是here