jquery在创建之前看到元素

时间:2014-12-12 02:47:46

标签: jquery

点击搜索字段时,我正在创建一个下拉框。我还有一个文档点击功能,可以在点击页面上的任何位置时报告下拉框的长度。为什么当第一次点击进入该搜索字段时,我的测试表明长度= 1? 我不知道如何更好地解释而不是显示代码。

$(document).click(function(){
if($('#suggestionBox').length == 1){
    console.log("YODER " + $('#suggestionBox').length);
    console.log("YODER CLICKY");
    }   
});

$(document).ready(function(){
    $('input.search-header-box').click(
        function(){
        if($('#suggestionBox').length == 0){
            $('#navMainSearch').append('<div id="suggestionBox"class="shadow"><ul><li><a>Ideas</a></li><li><a>More Ideas</a></li></ul></div>');
        //console.log("YODER");
        }   
    });
});

1 个答案:

答案 0 :(得分:0)

这是因为event bubbling

当您单击input元素时,首先调用$('input.search-header-box').click()处理程序,将目标元素添加到dom,然后将click事件冒泡到达到最后到达的祖先元素$(document).click(function(){})处理程序,当你查询dom时它已经存在,因此它显示为1。

&#13;
&#13;
$(document).click(function() {
  if ($('#suggestionBox').length == 1) {
    log("YODER " + $('#suggestionBox').length);
    log("YODER CLICKY");
  }
});

$(document).ready(function() {
  $('input.search-header-box').click(function() {
      if ($('#suggestionBox').length == 0) {
        log('Inside input click')
        $('#navMainSearch').append('<div id="suggestionBox"class="shadow"><ul><li><a>Ideas</a></li><li><a>More Ideas</a></li></ul></div>');
        //console.log("YODER");
      }
    });
});



var log = (function () {
    var $log = $('#log');
    return function (msg) {
        $('<p/>', {text: msg}).appendTo($log)
    }
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="search-header-box" type="button" value="Click" />
<div id="navMainSearch"></div>
<div id="log"></div>
&#13;
&#13;
&#13;

如果您不想要此行为,则可以通过调用event.stopPropagation()

来阻止冒泡

&#13;
&#13;
$(document).click(function() {
  if ($('#suggestionBox').length == 1) {
    log("YODER " + $('#suggestionBox').length);
    log("YODER CLICKY");
  }
});

$(document).ready(function() {
  //we want to add the element only once, so use .one() to register the handler
  $('input.search-header-box').one('click', function(e) {
    e.stopPropagation();
    if ($('#suggestionBox').length == 0) {
      log('Inside input click')
      $('#navMainSearch').append('<div id="suggestionBox"class="shadow"><ul><li><a>Ideas</a></li><li><a>More Ideas</a></li></ul></div>');
      //console.log("YODER");
    }
  });
});



var log = (function() {
  var $log = $('#log');
  return function(msg) {
    $('<p/>', {
      text: msg
    }).appendTo($log)
  }
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="search-header-box" type="button" value="Click" />
<div id="navMainSearch"></div>
<div id="log"></div>
&#13;
&#13;
&#13;