输入焦点警报,没有类别或ID,在Div内
How can I alert a message once the input is focused, of the following HTML code:
以下HTML代码如何在输入聚焦后提醒消息:
<div class="ss_datesel_inp_cont">
<div class="ss_datesel_inp_right_corner"> </div>
<input autocomplete="off">
</div>
This is what I tried but none works:
这是我尝试但没有效果:
$(".ss_datesel_inp_cont:input").click(function() {
alert("focused");
});
// or
$(".ss_datesel_inp_cont:input").focus(function() {
alert("focused");
});
//or
$(".ss_datesel_inp_cont").find("input").focus(function() {
alert("focused");
});
2 个解决方案
#1
2
The :input
selector will only work if the the given element is an input (also textarea, select, and others). The .ss_datesel
etc. class is not on the input, it's on the div. You can simply use a descendant selector instead:
:输入选择器仅在给定元素是输入(也是textarea,select和其他)时才起作用。 .ss_datesel等类不在输入上,它在div上。您只需使用后代选择器:
$(".ss_date_etc input").click(function() { alert('focused'); });
However, this will only work if click the input. If you focus it by tabbing or automatically, the alert won't occur. Problem is, if you use .focus
, alert()
steals the focus and then reapplies it in some browsers and you will be stuck in a focus loop. Here's a simple solution:
但是,这仅在单击输入时才有效。如果您通过Tab键或自动对焦,则不会发出警报。问题是,如果使用.focus,则alert()会窃取焦点,然后在某些浏览器中重新应用它,您将陷入焦点循环。这是一个简单的解决方案:
$(".ss_date_etc input").focus(function () {
if (!$(this).data('focused')) {
$(this).data('focused', true);
alert('focus!');
}
});
Note that not all browsers will restore focus after an alert, even if you try to force them to. You may want to use some alternative to alert
, especially because that would be really annoying to users.
请注意,并非所有浏览器都会在警报后恢复焦点,即使您尝试强制它们也是如此。您可能希望使用一些替代警报,特别是因为这对用户来说真的很烦人。
You can also update .data('focused')
to false
on blur so this happens over again.
您还可以在模糊时将.data('focused')更新为false,这样就会再次发生。
更多相关文章
- 谷歌Chrome复制了JavaScript的“焦点”事件
- ASP.NET文本框不会失去焦点
- 我如何捕获并插入Meteor.Error警报从Meteor.Methods到客户端数据
- 在AngularJS中轻松控制dom - 单击按钮,然后将焦点设置为输入元素
- Javascript警报中文本的颜色
- 如何在onchange()事件后调用的方法中将焦点设置为输入字段?
- 自定义ComboBox焦点不会切换到选择elem并且eventBubble不会停止
- 在contenteditable中的占位符—焦点事件问题