Javascript用document.onclick关闭下拉列表

时间:2018-06-01 00:31:05

标签: javascript jquery toggle dropdown document

我有一个使用ul和li的下拉列表:

<img class="options_toggle" src="assets/down_arrow.png"onclick="toggle_display('options');"/>

<ul id="options" class="options_content hide">
      <li>
           option one
      </li>
</ul>

options_toggle函数在&#34; hide&#34;之间来回切换。并且&#34;显示&#34;选项ul中的类。现在我想只在用户点击除选项切换之外的任何地方时隐藏它:

$(document).ready(function () {
document.onclick = function(e) {

    // prevent the dropdown from closing instantly when you click the toggle to open it
    $(".options_toggle").click(function (e) {
        e.stopPropagation();
    });

    // hide the dropdown
    $(".options_content").removeClass("show");
    $(".options_content").addClass("hide");
};
});

但问题是,在第一次加载页面时,他们必须在点击切换之前单击某处。第一次点击后,它工作正常,他们只需要先点击两次,这可能很烦人。

任何想法是什么以及为什么取消或忽略第一次切换?感谢。

1 个答案:

答案 0 :(得分:1)

在另一个事件处理程序中添加事件处理程序通常是错误的。只需将您的$(".options_toggle").click()处理程序绑定在顶层。

$(document).ready(function() {
  $(".options_toggle").click(function(e) {
    // prevent the dropdown from closing instantly when you click the toggle to open it
    e.stopPropagation();
  });

  $(document).click(function(e) {
    // hide the dropdown
    $(".options_content").removeClass("show");
    $(".options_content").addClass("hide");
  });
});