在我的网络应用程序上,我有一个屏幕,希望用户使用条形码扫描仪来扫描项目编号,但如果他们没有(或代码无法扫描),他们可以单击要求他们扫描的通知,它会变成一个框,允许他们输入详细信息以手动搜索。
问题是,事件侦听器似乎应用于关闭按钮,它从 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();” 手动它工作正常。
你需要在你的 js 中做一些改变。首先.one
更改为.on
第二个需要更改关闭功能单击事件,因为搜索表单是用js添加到dom的,因此您需要像这样在其上触发click事件$(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;
}
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句