Javascript 您如何检测“搜索”HTML5 输入的清除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2977023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you detect the clearing of a "search" HTML5 input?
提问by Jason
In HTML5, the searchinput type appears with a little X on the right that will clear the textbox (at least in Chrome, maybe others). Is there a way to detect when this X is clicked in Javascript or jQuery other than, say, detecting when the box is clicked at all or doing some sort of location click-detecting (x-position/y-position)?
在 HTML5 中,search输入类型会在右侧显示一个小 X 以清除文本框(至少在 Chrome 中,也许其他人中如此)。有没有办法检测何时在 Javascript 或 jQuery 中单击此 X,而不是检测何时单击框或进行某种位置单击检测(x 位置/y 位置)?
采纳答案by Pauan
Actually, there is a "search" event that is fired whenever the user searches, or when the user clicks the "x". This is especially useful because it understands the "incremental" attribute.
实际上,每当用户搜索或用户单击“x”时都会触发“搜索”事件。这特别有用,因为它理解“增量”属性。
Now, having said that, I'm not sure if you can tell the difference between clicking the "x" and searching, unless you use an "onclick" hack. Either way, hopefully this helps.
现在,话虽如此,我不确定您是否能分辨出单击“x”和搜索之间的区别,除非您使用“onclick”技巧。无论哪种方式,希望这会有所帮助。
References:
参考:
回答by Sharad Biradar
Bind search-event the search box as given below-
绑定-search事件搜索框,如下所示-
$('input[type=search]').on('search', function () {
// search logic here
// this function will be executed on click of X (clear button)
});
回答by Lorenzo Dematté
I want to add a "late" answer, because I struggled with change, keyupand searchtoday, and maybe what I found in the end may be useful for others too.
Basically, I have a search-as-type panel, and I just wanted to react properly to the press of the little X (under Chrome and Opera, FF does not implement it), and clear a content pane as a result.
我想添加一个“迟到”的答案,因为我挣扎change,keyup和search今天,也许是我最后发现可能对他人有用的。基本上,我有一个搜索类型面板,我只是想对小 X 的按下做出正确的反应(在 Chrome 和 Opera 下,FF 没有实现它),并因此清除内容窗格。
I had this code:
我有这个代码:
$(some-input).keyup(function() {
// update panel
}
$(some-input).change(function() {
// update panel
}
$(some-input).on("search", function() {
// update panel
}
(They are separate because I wanted to check when and under which circumstances each was called).
(它们是分开的,因为我想检查每个调用的时间和情况)。
It turns out that Chrome and Firefox react differently.
In particular, Firefox treats changeas "every change to the input", while Chrome treats it as "when focus is lost AND the content is changed".
So, on Chrome the "update panel" function was called once, on FF twice for every keystroke (one in keyup, one in change)
事实证明,Chrome 和 Firefox 的反应不同。特别是,Firefox 将其change视为“对输入的每次更改”,而 Chrome 将其视为“当焦点丢失且内容更改时”。因此,在 Chrome 上,“更新面板”功能被调用一次,每次击键在 FF 上调用两次(一个 in keyup,一个 in change)
Additionally, clearing the field with the small X (which is not present under FF) fired the searchevent under Chrome: no keyup, no change.
此外,用小 X 清除字段(在 FF 下不存在)会search在 Chrome下触发事件: no keyup, no change。
The conclusion? Use inputinstead:
结论?使用input来代替:
$(some-input).on("input", function() {
// update panel
}
It works with the same behaviour under all the browsers I tested, reacting at every change in the input content (copy-paste with the mouse, autocompletion and "X" included).
它在我测试过的所有浏览器下以相同的行为工作,对输入内容的每次更改做出反应(使用鼠标复制粘贴、自动完成和“X”)。
回答by ggutenberg
Using Pauan's response, it's mostly possible. Ex.
使用 Pauan 的回应,这几乎是可能的。前任。
<head>
<script type="text/javascript">
function OnSearch(input) {
if(input.value == "") {
alert("You either clicked the X or you searched for nothing.");
}
else {
alert("You searched for " + input.value);
}
}
</script>
</head>
<body>
Please specify the text you want to find and press ENTER!
<input type="search" name="search" onsearch="OnSearch(this)"/>
</body>
回答by lostInTheTetons
I know this is an old question, but I was looking for the similar thing. Determine when the 'X' was clicked to clear the search box. None of the answers here helped me at all. One was close but also affected when the user hit the 'enter' button, it would fire the same result as clicking the 'X'.
我知道这是一个老问题,但我一直在寻找类似的东西。确定何时单击“X”以清除搜索框。这里的任何答案都没有帮助我。一个是关闭的,但当用户点击“输入”按钮时也会受到影响,它会触发与点击“X”相同的结果。
I found this answer on another post and it works perfect for me and only fires when the user clears the search box.
我在另一篇文章中找到了这个答案,它非常适合我,并且仅在用户清除搜索框时触发。
$("input").bind("mouseup", function(e){
var $input = $(this),
oldValue = $input.val();
if (oldValue == "") return;
// When this event is fired after clicking on the clear button
// the value is not cleared yet. We have to wait for it.
setTimeout(function(){
var newValue = $input.val();
if (newValue == ""){
// capture the clear
$input.trigger("cleared");
}
}, 1);
});
回答by Cory Gagliardi
It made sense to me that clicking the X should count as a change event. I already had the onChange event all setup to do what I needed it to do. So for me, the fix was to simply do this jQuery line:
对我来说,单击 X 应该算作更改事件是有道理的。我已经设置了 onChange 事件来完成我需要它做的事情。所以对我来说,解决方法是简单地做这个 jQuery 行:
$('#search').click(function(){ $(this).change(); });
$('#search').click(function(){ $(this).change(); });
回答by mVChr
It doesn't seem like you can access this in browser. The search input is a Webkit HTML wrapper for the Cocoa NSSearchField. The cancel button seems to be contained within the browser client code with no external reference available from the wrapper.
您似乎无法在浏览器中访问它。搜索输入是 Cocoa NSSearchField 的 Webkit HTML 包装器。取消按钮似乎包含在浏览器客户端代码中,包装器中没有可用的外部引用。
Sources:
资料来源:
- http://weblogs.mozillazine.org/hyatt/archives/2004_07.html#005890
- http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#text-state-and-search-state
- http://dev.w3.org/html5/markup/input.search.html#input.search
- http://weblogs.mozillazine.org/hyatt/archives/2004_07.html#005890
- http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#text-state-and-search-state
- http://dev.w3.org/html5/markup/input.search.html#input.search
Looks like you'll have to figure it out through mouse position on click with something like:
看起来你必须通过点击鼠标的位置来弄清楚:
$('input[type=search]').bind('click', function(e) {
var $earch = $(this);
var offset = $earch.offset();
if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
// your code here
}
});
回答by ScottG
Found this post and I realize it's a bit old, but I thinkI might have an answer. This handles the click on the cross, backspacing and hitting the ESC key. I am sure it could probably be written better - I'm still relatively new to javascript. Here is what I ended up doing - I am using jQuery (v1.6.4):
找到这篇文章,我意识到它有点旧,但我想我可能有答案。这将处理点击十字、退格和按下 ESC 键。我相信它可能会写得更好 - 我对 javascript 还是比较陌生。这是我最终做的 - 我正在使用 jQuery (v1.6.4):
var searchVal = ""; //create a global var to capture the value in the search box, for comparison later
$(document).ready(function() {
$("input[type=search]").keyup(function(e) {
if (e.which == 27) { // catch ESC key and clear input
$(this).val('');
}
if (($(this).val() === "" && searchVal != "") || e.which == 27) {
// do something
searchVal = "";
}
searchVal = $(this).val();
});
$("input[type=search]").click(function() {
if ($(this).val() != filterVal) {
// do something
searchVal = "";
}
});
});
回答by James Yang
based on event-loop of js, the clickon clear button will trigger searchevent on input, so below code will work as expected:
基于 js 的事件循环,click清除按钮将search在input上触发事件,因此下面的代码将按预期工作:
input.onclick = function(e){
this._cleared = true
setTimeout(()=>{
this._cleared = false
})
}
input.onsearch = function(e){
if(this._cleared) {
console.log('clear button clicked!')
}
}
The above code, onclickevent booked a this._cleared = falseevent loop, but the event will always run afterthe onsearchevent, so you can stably check the this._clearedstatus to determine whether user just clicked on Xbutton and then triggered a onsearchevent.
上面的代码,的onclick事件预订一个this._cleared = false事件循环,但该事件将永远运行后的onsearch事件,这样你就可以稳定地检查this._cleared状态,以确定用户是否只是点击X按钮,然后触发一个onsearch事件。
This can work on almost all conditions, pasted text, has incrementalattribute, ENTER/ESCkey press etc.
这几乎适用于所有条件、粘贴文本、具有增量属性、ENTER/ESC按键等。
回答by Revanth
Here's one way of achieving this. You need to add incremental attribute to your html or it won't work.
这是实现这一目标的一种方法。您需要向 html 添加增量属性,否则它将无法工作。
window.onload = function() {
var tf = document.getElementById('textField');
var button = document.getElementById('b');
button.disabled = true;
var onKeyChange = function textChange() {
button.disabled = (tf.value === "") ? true : false;
}
tf.addEventListener('keyup', onKeyChange);
tf.addEventListener('search', onKeyChange);
}
<input id="textField" type="search" placeholder="search" incremental="incremental">
<button id="b">Go!</button>

