单击li元素后无法隐藏ul

时间:2016-11-24 14:12:48

标签: javascript jquery html

点击输入后我打开<ul>列表,需要点击<li>或其他屏幕位置关闭

这里我的JS&amp; HTML

&#13;
&#13;
$(".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();
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

$(".dropdown-list").hide(); - 这不起作用,我现在不知道为什么?

1 个答案:

答案 0 :(得分:2)

您需要将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
  });
});

&#13;
&#13;
$(function() {
  $(".drop-down-input input").click(function() {
    $(".dropdown-list").show();
  });
  $(".dropdown-list li").on('click', function() {
    $(".dropdown-list")
      .hide()
      .siblings('input')
      .val($(this).html());
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

或使用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());
  });
});

&#13;
&#13;
$(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());
  });
});
&#13;
<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>
&#13;
&#13;
&#13;