簡體   English   中英

單擊li元素后無法隱藏ul

[英]Can't hide ul after clicking li element

點擊輸入后我打開<ul>列表,需要在點擊<li>或在其他屏幕位置關閉它

這里是我的JS和HTML

 $(".drop-down-input").click(function() { $(".dropdown-list").show(); }); // get "li" value and set to input $(function() { $(".dropdown-list li").on('click', function() { $idinput = $(".dropdown-list").siblings('input').attr('id'); $idinput = '#' + $idinput; $($idinput).val($(this).html()); $(".dropdown-list").hide(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="styled-input-container drop-down-input"> <input id="simple_2" class="drop-down-select" placeholder="input text" type="text"> <ul class="dropdown-list"> <li>eeee</li> <li>xxxx</li> <li>xxxx</li> </ul> </div> 

$(".dropdown-list").hide(); - 這不行,我現在不知道為什么?

您需要將click事件綁定到input元素而不是整個div,否則可能會發生事件冒泡。 雖然實際上很簡單,但是不需要通過id值再次獲取id和select元素。

$(function() {
  $(".drop-down-input input").click(function() {
    $(".dropdown-list").show();
  });
  $(".dropdown-list li").on('click', function() {
    // if there is multiple `.dropdown-list` then get based on 
    // this context , eg : $(this).parent()
    $(".dropdown-list") 
      .hide() // hide the element
      .siblings('input') // get the sibling
      .val($(this).html()); // set it's value
  });
});

 $(function() { $(".drop-down-input input").click(function() { $(".dropdown-list").show(); }); $(".dropdown-list li").on('click', function() { $(".dropdown-list") .hide() .siblings('input') .val($(this).html()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="styled-input-container drop-down-input"> <input id="simple_2" class="drop-down-select" placeholder="input text" type="text"> <ul class="dropdown-list"> <li>eeee</li> <li>xxxx</li> <li>xxxx</li> </ul> </div> 


或者使用event.stopPropagation()來防止事件冒泡。

$(function() {
  $(".drop-down-input").click(function() {
    $(".dropdown-list").show();
  });
  $(".dropdown-list li").on('click', function(e) {
    e.stopPropagation();
    $(".dropdown-list")
      .hide()
      .siblings()
      .val($(this).html());
  });
});

 $(function() { $(".drop-down-input").click(function() { $(".dropdown-list").show(); }); $(".dropdown-list li").on('click', function(e) { e.stopPropagation(); $(".dropdown-list") .hide() .siblings() .val($(this).html()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="styled-input-container drop-down-input"> <input id="simple_2" class="drop-down-select" placeholder="input text" type="text"> <ul class="dropdown-list"> <li>eeee</li> <li>xxxx</li> <li>xxxx</li> </ul> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM