3

示例代码在这里: http ://codepen.io/vincentccw/pen/loAwu

基本上我想做的是使用标签但可替换的 div 按钮创建一个自定义下拉列表。

我的问题是,一旦我单击 div,将添加自定义类(出现下拉列表),但是当我第二次单击其他任何地方时,我想删除该类并因此恢复到原始状态。我该怎么做?

$(function(){ 

$(".dButton").click(function(){
   $("div ul.customDropDownList").addClass("clickButtonReveal");
});     
$('body').click(function(){
if( $("div ul.customDropDownList").hasClass("clickButtonReveal") ){
      alert("remove class");
      $("div ul.customDropDownList").removeClass("clickButtonReveal");
      };
    });
}); 

现在这两个点击功能将同时触发....

4

4 回答 4

4

您可以在按钮单击时停止传播:

$(".dButton").click(function (e) {
    e.stopPropagation();
    $("div ul.customDropDownList").addClass("clickButtonReveal");

});
于 2013-06-17T10:47:54.983 回答
4

试试这个

$(".dButton").click(function (e) {
    e.stopPropagation();
    $("div ul.customDropDownList").addClass("clickButtonReveal");

});

更新以下内容:

了解更多信息

于 2013-06-17T10:49:42.377 回答
3

你可以试试这个并检查你的点击目标的ID:

html:

<div id="test">

</div>

CSS:

#test{
    background-color:red;
    width:200px;
    height:200px;
}

javascript:

$(document).ready(function(){
    $(document).click(function(e){
       if(e.target.id == 'test')
       {
           alert('Red box clicked!');
       }
       else
       {
           alert('Clicked something else');
       }
    })
})

这里的工作示例:

http://jsfiddle.net/JXZhP/

于 2013-06-17T10:53:03.783 回答
0

当用户单击页面正文的任何​​位置时,使用 jQuery one() 函数删除您需要删除的任何内容。one() 仅触发一次...因此将代码更改为:

$(".dButton").click(function(){
  $("div ul.customDropDownList").addClass("clickButtonReveal");
  $('body').one(function(){
    $("div ul.customDropDownList").removeClass("clickButtonReveal")
  });
}); 

以防万一不清楚:删除$('body').click(function(){...})代码中的第二个函数。这将替换您的所有代码。

于 2013-06-17T10:44:31.060 回答