点击不起作用的嵌套li值

时间:2016-11-22 09:18:00

标签: javascript jquery html html-lists

我有嵌套li元素的元素,我做了一个click函数来获取值。每次我点击我都会一次又一次地获得相同的价值。

<script type="text/javascript">

    $('.cat-select').on('click',function(){
        $('.cat-list').css('display','block');
         $('.sub-list').css('display','block');

    });

    $(document).on('click','.cat-list>li',function(){
        var selectedVal = $(this).clone()   //clone the element
            .children() //select all the children
            .remove()   //remove all the children
            .end()  //again go back to selected element
            .text();    //get the text of elemen
        console.log(selectedVal);
        $('.cat-select').text(selectedVal);
    });
</script>


<div class="form-group">
   <label for="input-placeholder" class="col-sm-2 control-label"></label>
    <div class="col-sm-10"> 
        <style type="text/css">
            .cat-list, .sub-list{ display: none; }
        </style>
        <div class="cat-group">
            <button class="cat-select" type="button">Select Category</button>
            <ul class="cat-list">
                <li class="have-child">Electronics 
                    <ul class="sub-list">
                        <li class="have-child"> Mobiles & Tablets
                            <ul class="sub-list">
                                <li>Mobiles</li>
                                <li>Tablets</li>
                                <li class="have-child">Accessories</li>
                                    <ul>
                                        <li>Power Bank</li>
                                        <li>Phone Cases</li>
                                    </ul>
                            </ul>
                        </li>
                        <li class="have-child">Cameras
                            <ul class="sub-list">
                                <li>DSLRs</li>
                                <li>Drones</li>
                            </ul>
                        </li>
                    </ul>
                </li>        
            </ul>
        </div>
    </div>
</div>

每次点击我都会得到相同的值

https://jsfiddle.net/yx4Ldt80/

4 个答案:

答案 0 :(得分:3)

您看到的问题是因为您只通过使用.cat-list运算符将事件处理程序附加到>的子项。

要解决此问题,请从选择器中删除它并在事件上调用stopPropagation()以阻止它冒泡DOM。试试这个:

$(document).on('click', '.cat-list li', function(e) {
    e.stopPropagation();
    var selectedVal = $(this).clone().children().remove().end().text();
    $('.cat-select').text(selectedVal);
})

&#13;
&#13;
$('.cat-select').on('click', function() {
  $('.cat-list, .sub-list').toggle();
});

$(document).on('click', '.cat-list li', function(e) {
  e.stopPropagation();
  var selectedVal = $(this).clone().children().remove().end().text();
  $('.cat-select').text(selectedVal);
})
&#13;
.cat-list,
.sub-list {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="form-group">
  <label for="input-placeholder" class="col-sm-2 control-label"></label>

  <div class="col-sm-10">
    <div class="cat-group">
      <button class="cat-select" type="button">Select Category</button>

      <ul class="cat-list">
        <li class="have-child">Electronics
          <ul class="sub-list">
            <li class="have-child">
              Mobiles &amp; Tablets
              <ul class="sub-list">
                <li>Mobiles</li>
                <li>Tablets</li>
                <li class="have-child">Accessories
                  <ul>
                    <li>Power Bank</li>
                    <li>Phone Cases</li>
                  </ul>
                </li>
              </ul>
            </li>
            <li class="have-child">
              Cameras
              <ul class="sub-list">
                <li>DSLRs</li>
                <li>Drones</li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

另请注意,我已在您的&#39;附件&#39;中修复了HTML。 ul,因为它位于父li之外。

答案 1 :(得分:1)

从不使用Node *ListDelete(Node *list, Node *tail, int val, Node **deleted) { // special case empty and singleton lists if (!list || (list == list->next && list->value != val)) { *deleted = NULL; return list; } if (list == list->next) { *deleted = list; return NULL; } for (Node *node = list;; node = node->next) { if (node->next->value == val) { *deleted = node->next; node->next = node->next->next; if (list == *deleted) list = node->next; return list; } else if (node == tail) { // equivalent to if (node->next == list) *deleted = NULL; return list; } } }

最糟糕的事情就是使用Event.stopPropagation()。(如此处以及网上的答案所建议)。
除非您真的知道自己在做什么,否则请不要使用Event.stopPropagation()

应用程序应该始终意识到在其上下文中发生的每个事件。
假设您构建了一个弹出窗口,模式窗口或自定义选择框,如果您单击页面中的其他任何位置,都需要关闭该框。好的,恭喜,一个LI元素阻止了您这样做。

改为使用Event.stopPropagation()

Event.target

以下是您特定用例的示例:

function myClickHandler(ev) {
  if (ev.target !== this) return; // Ignore if non-this called the event
  console.log( this.textContent );
}
const $cat = $('.cat-select');

$cat.on('click', function() {
  $('.cat-list, .sub-list').toggle();
});

$(document).on('click', '.cat-list li', function(ev) {
  if (ev.target !== this) return; // Ignore if non-this called the event
  const value = $(this).contents().filter((i, el) => el.nodeType == 3)[0].nodeValue;
  $cat.text(value);
});


// Than, 3000 lines later... THANK YOU BECAUSE:
$('body').on('click', function() {
  // Close a popup or something 
  console.clear(); console.log(`YEY I registered an event!
  Thank you for not using Event.preventDefault()`);
});
.cat-list, 
.sub-list  {
  display: none;
}

答案 2 :(得分:0)

根据event.target属性获取点击的元素。虽然您可以通过contents()filter()方法避免克隆,这有助于过滤掉文本节点。

$(document).on('click', 'li', function(e) {
  // if target element is not `li` tag then get closest li tag
  var selectedVal = (e.target.nodeType == 'LI' ? $(e.target) : $(e.target).closest('li'))
    .contents() // get all children nodes 
    .filter(function() { // filter  out text nodes
      return this.nodeType === 3;
    }).text(); // get text content

  $('.cat-select').text(selectedVal);
})

&#13;
&#13;
$(document).on('click', 'li', function(e) {
  // if target element is not `li` tag then get closest li tag
  var selectedVal = (e.target.nodeType == 'LI' ? $(e.target) : $(e.target).closest('li'))
    .contents() // get all children nodes 
    .filter(function() { // filter  out text nodes
      return this.nodeType === 3;
    }).text(); // get text content

  $('.cat-select').text(selectedVal);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="input-placeholder" class="col-sm-2 control-label"></label>

  <div class="col-sm-10">
    <div class="cat-group">
      <button class="cat-select" type="button">
        Select Category</button>

      <ul class="cat-list">
        <li class="have-child">Electronics
          <ul class="sub-list">
            <li class="have-child">Mobiles & Tablets
              <ul class="sub-list">
                <li>Mobiles</li>
                <li>Tablets</li>
                <li class="have-child">Accessories</li>
                <ul>
                  <li>Power Bank</li>
                  <li>Phone Cases</li>
                </ul>
              </ul>
            </li>
            <li class="have-child">Cameras
              <ul class="sub-list">
                <li>DSLRs</li>
                <li>Drones</li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我希望这个人能帮助你

$('.cat-select').each(function() {
    $(this).on('click', function() {
    $('.cat-list').css('display', 'block');
    $('.sub-list').css('display', 'block');
    });
});
$(document).on('click', function() {
    $(this).each('.cat-list li', function() {
      var selectedVal = $(this).clone() //clone the element
        .children() //select all the children
        .remove() //remove all the children
        .end() //again go back to selected element
        .text(); //get the text of elemen
        console.log(selectedVal);
        $('.cat-select').text(selectedVal);
    });
});