在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?
当前回答
完整的解决方案在这里
这将在单击搜索x时清除搜索。 或 当用户按回车键时,将调用搜索API。 这段代码可以通过附加的esc键up事件匹配器进一步扩展。但是这个应该能搞定。
document.getElementById("userSearch").addEventListener("search",
function(event){
if(event.type === "search"){
if(event.currentTarget.value !== ""){
hitSearchAjax(event.currentTarget.value);
}else {
clearSearchData();
}
}
});
欢呼。
其他回答
点击TextField交叉按钮(X) onmousemove()被触发,我们可以使用这个事件来调用任何函数。
<input type="search" class="actInput" id="ruleContact" onkeyup="ruleAdvanceSearch()" placeholder="Search..." onmousemove="ruleAdvanceSearch()"/>
将搜索事件绑定到搜索框,如下所示-
$('input[type=search]').on('search', function () {
// search logic here
// this function will be executed on click of X (clear button)
});
const inputElement = document.getElementById("input");
let inputValue;
let isSearchCleared = false;
inputElement.addEventListener("input", function (event) {
if (!event.target.value && inputValue) {
//Search is cleared
isSearchCleared = true;
} else {
isSearchCleared = false;
}
inputValue = event.target.value;
});
搜索或onclick工作…但我发现的问题是旧的浏览器——搜索失败。很多插件(jquery ui autocomplete或fancytree filter)都有模糊和聚焦处理程序。将其添加到自动完成输入框对我来说很有效。Value == ""因为它的计算速度更快)。当你点击小“x”时,模糊然后聚焦将光标保持在方框中。
PropertyChange和input在IE 10和IE 8以及其他浏览器上都可以工作:
$("#INPUTID").on("propertychange input", function(e) {
if (this.value == "") $(this).blur().focus();
});
对于FancyTree过滤器扩展,你可以使用一个重置按钮,并强制它的点击事件如下:
var TheFancyTree = $("#FancyTreeID").fancytree("getTree");
$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
var n,
leavesOnly = false,
match = $(this).val();
// check for the escape key or empty filter
if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
$("button#btnResetSearch").click();
return;
}
n = SiteNavTree.filterNodes(function (node) {
return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
}, leavesOnly);
$("button#btnResetSearch").attr("disabled", false);
$("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();
// handle the reset and check for empty filter field...
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
if ($("input[name=FT_FilterINPUT]").val() != "")
$("input[name=FT_FilterINPUT]").val("");
$("span#SiteNavMatches").text("");
SiteNavTree.clearFilter();
}).attr("disabled", true);
应该能够适应这为大多数用途。
实际上,每当用户搜索或单击“x”时,都会触发一个“search”事件。这特别有用,因为它理解“增量”属性。
现在,话虽如此,我不确定你是否能说出点击“x”和搜索之间的区别,除非你使用“onclick”黑客。不管怎样,希望这对你有所帮助。
多托罗网络参考
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 如何在JSON中使用杰克逊更改字段名
- CSS在特定的“内联块”项之前/之后换行
- 很好的初学者教程socket.io?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- 我如何删除背景图像在css?
- 如何克服HTML表单嵌套的限制?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?