jQuery事件侦听器是否粘连/层叠?

时间:2019-01-23 08:00:05

标签: javascript jquery

在我的Web应用程序上,我有一个屏幕,期望用户使用条形码扫描仪扫描其中的物品编号,但是如果他们没有一个(或者代码不会扫描),则可以单击要求他们进行扫描的通知,它会变成一个框,允许他们输入要手动搜索的详细信息。

问题是,事件侦听器似乎已应用于关闭按钮,它已从div中删除,但关闭按钮似乎调用了“打开搜索框”功能,而不是“关闭搜索框”功能

我尝试使用jQuery $('#id').one('click' function(){myFunctionHere();});函数在单击DIV时添加事件侦听器,还尝试使用$('#id').on('click' function(){myFunctionHere();});$('#id').off('click');,但是我遇到了同样的问题。

请参见jsfiddle

<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<style>
#tnt-searchScan{
  width: 300px;
  height: 100px;
  border: 5px dashed red;
  text-align: center;
}
</style>
<script>
$(document).ready(function(){
    $('#tnt-searchScan').one('click', function(){showSearchBox();});
})

function closeSearchBox(){
  var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
  $('#tnt-searchScan').html(html).one('click', function(){showSearchBox();});
}

function showSearchBox(){
  console.log('test');
  var html = 'Content of search box<button type="button" id="tnt-closeSearchBox">Close</button>';
  $('#tnt-searchScan').html(html);
  $('#tnt-closeSearchBox').one('click', function(){closeSearchBox();});
}
</script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>

我希望该框恢复正常,但如果您单击控制台,则每次单击“关闭”时都不会,但不会出现“测试”,表明已调用show函数。如果我叫“ closeSearchBox();”手动可以正常工作。

1 个答案:

答案 0 :(得分:1)

您需要在js中进行一些更改。首先将.one更改为.on,其次需要更改关闭函数click事件,因为搜索表单是在dom中添加了js,因此您需要像这样{{1} }。

$(document).on('click','#tnt-closeSearchBox', function(){ closeSearchBox(); });
$(document).ready(function(){
    $('#tnt-searchScan').on('click', function(){showSearchBox();});
})

function closeSearchBox(){
  var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
  $('#tnt-searchScan').html(html).on('click', function(){showSearchBox();});
}

function showSearchBox(){
  //console.log('test');
  var html = '<label>Search By: <select id="tnt-searchOption">' +
      '<option selected>ID</option>' +
      '<option>Legacy ID</option>' +
      '</select></label>' +
      '<label>Search: <input type="text" id="tnt-searchBox"></label>' +
      '<button type="button">Search</button><button type="button" id="tnt-closeSearchBox">Close</button>';
  $('#tnt-searchScan').html(html);
}
  $(document).on('click','#tnt-closeSearchBox', function(){closeSearchBox();});
#tnt-searchScan{
  width: 300px;
  height: 100px;
  border: 5px dashed red;
  text-align: center;
}