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,这样就会再次发生。

更多相关文章

  1. 谷歌Chrome复制了JavaScript的“焦点”事件
  2. ASP.NET文本框不会失去焦点
  3. 我如何捕获并插入Meteor.Error警报从Meteor.Methods到客户端数据
  4. 在AngularJS中轻松控制dom - 单击按钮,然后将焦点设置为输入元素
  5. Javascript警报中文本的颜色
  6. 如何在onchange()事件后调用的方法中将焦点设置为输入字段?
  7. 自定义ComboBox焦点不会切换到选择elem并且eventBubble不会停止
  8. 在contenteditable中的占位符—焦点事件问题

随机推荐

  1. Android 之 SeekBar用法介绍
  2. Android 7.1.2(Android N) Android系统启
  3. Android安装
  4. Android 控件常用属性
  5. JAVA & Android 系统环境变量配置
  6. Android 7.1 去掉桌面上的谷歌搜索框
  7. Android实时获得周围wifi信息(SSID,强度等)
  8. android 塔防游戏汇总 及android 游戏开
  9. 【Android】【Framework】Android_Framew
  10. android图片切换ImageSwichter的动画切换