简体   繁体   English

为什么jQuery下拉列表需要两次单击?

[英]Why does jQuery dropdown require two clicks?

When I click on the button labeled "Continents & Oceans," a dropdown list appears - but only if I click on the button twice. 当我单击标记为“大陆和海洋”的按钮时,将显示一个下拉列表-但仅当我单击两次按钮时。 I'd like it to work with the first click. 我希望它可以与第一次点击一起使用。

Is there something wrong with my code, or do I need to add something to make the dropdown drop down on the first click? 我的代码是否有问题,还是我需要添加一些内容以使下拉列表在首次点击时就被下拉?

This is a jQuery function, but it also includes my first experiment with AJAX, so maybe that's the problem. 这是一个jQuery函数,但它也包括我的第一个AJAX实验,所以也许就是问题所在。

<input type = "button" id = "konoce" value = "Continents &amp; Oceans" class="btn btn-konoce"
<div id = "div-konoce"> </div>

<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
  $("#konoce").click(function(event) {
    if ($('#div-konoce').html() == '') {
      $.get( "/2b/inc/ajax/db-lists/world/konoce.php", { name: "KonOce"     }, function(data) {
    $('#div-konoce').html(data);
   });
   }
    else {
      $('#div-konoce').html('');
    }
  });            
});
</script>

EDIT: 编辑:

I revised my code per the answer below. 我根据以下答案修改了代码。 However, it still takes two clicks to open the dropdown. 但是,仍然需要单击两次才能打开下拉列表。

<button type = "button" id = "konoce" class="btn btn-konoce">Continents &amp; Oceans</button>
<div id = "div-konoce" style="margin: 0 -5px;"> </div>

Your line: 您的电话:

if ($('#div-konoce').html() == '')

checks if the "div-konoce" div is empty, but it's not: 检查“ div-konoce” div是否为空,但不是:

<div id = "div-konoce"> </div>

There's a space there... meaning not == '' 那里有一个空格...不是==''

Remove the space and try again. 删除空间,然后重试。

you are not closing your input - it should be: 您没有关闭输入-应该是:

<input type = "button" id = "konoce" value = "Continents &amp; Oceans" class="btn btn-konoce" />

and I am not sure why you have this as an input and not a button, since it not used to gather information - but acts as a trigger fo the click.: 而且我不确定为什么您将其作为输入而不是按钮,因为它不是用来收集信息的,而是作为单击的触发器。

<button type = "button" id = "konoce" class="btn btn-konoce">Continents &amp; Oceans</button>

One tip is ,Why are you always emptying $('#div-konoce') , it will cause one ajax request per click . 一个提示是,为什么您总是清空$('#div-konoce') ,这将导致每次单击请求一个ajax请求。 But if you only wrote the first if , it will show the previously loaded menu after the first click onwards . 但是,如果您只写了第一个if ,则在第一次单击后它将显示以前加载的菜单。

 <div id = "div-konoce"></div>
   if ($('#div-konoce').html()=='') {
      $.get( "/2b/inc/ajax/db-lists/world/konoce.php", { name: "KonOce"     }, function(data) {
    $('#div-konoce').html(data);
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM