第二次点击后,jquery切换功能无效

时间:2018-04-20 17:40:04

标签: jquery html

我创建一个简单的下拉菜单,从1到6中选择一个数字。问题是,在第二次点击后,切换命令不起作用,ul仍然消失。

HTML

<div id="selectDiv">1
  <ul id="select">
    <li class="liNum">1</li>
    <li class="liNum">2</li>
    <li class="liNum">3</li>
    <li class="liNum">4</li>
    <li class="liNum">5</li>
    <li class="liNum">6</li>
  </ul>
</div>

CSS

#selectDiv {
  position: relative;
  text-align: center;
  width: 8vw;
  height: 100%;
  background-color: #616160;
  color: white;
}

#select {
  position: absolute;
  padding: 0;
  top: 105%;
  left: 0;
  list-style: none;
  display: none;
}

#select>li {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #616160;
  border-bottom: 0.2px solid #3cb4e4;
  width: 8vw;
  height: 8vw;
}

#select>li:hover {
  background-color: #FFAA00;
}

JQUERY

$('#selectDiv').click(function() {
    $('#select').toggle();
  });

  $('.liNum').on('click', function(event) {
   event.stopPropagation(); // disable or enable makes no difference
    var txt = $(this).html();
    $('#selectDiv').html(txt);
  });

我还创建了jsfiddle

1 个答案:

答案 0 :(得分:1)

问题是$('#selectDiv')。html(txt)没有切换,它会删除该div中的所有内容,包括列表,并将其替换为所选的整数。相反,尝试在自己的标签中轻松修改1,并且在修改后不要忘记调用切换:

HTML

<div id="selectDiv"><span id="result">1</span>
 <ul id="select">
  <li class="liNum">1</li>
  <li class="liNum">2</li>
  <li class="liNum">3</li>
  <li class="liNum">4</li>
  <li class="liNum">5</li>
  <li class="liNum">6</li>
 </ul>
</div>

JQuery的

$('#selectDiv').click(function() {
  $('#select').toggle();
});

$('.liNum').on('click', function(event) {
  event.stopPropagation();
  var txt = $(this).html();
  $('#result').html(txt);
  $('#select').toggle();
});