javascript - 点击被忽略 : Issue with label elements to associate with form controls

标签 javascript jquery html css

我已使用“for”属性将标签元素关联到表单字段。当我在表单字段下方显示验证消息时,会出现此问题。

例如,在下面的演示中,表单字段 1 需要验证 onblur,

  1. 通过点击标签选择表单字段 1
  2. 现在单击表单字段 2 标签,该标签应将焦点设置到表单字段 2,但焦点未设置并且单击被忽略.

有什么想法吗?

$(function () {
	$('#formfield1').blur(function() {
   	$('#errorMessage').text('Form field is required').show();
  });
  var counter = 1;
  $('*').on('focus blur', function (e) {
  	console.log(counter++ + ' ' + e.type + ' ' + this.id);
  })
  
  $('*').click(function (e) {
     e.stopImmediatePropagation()
     console.log(counter++ + ' ' + e.target.id + ' clicked ');
  });
});
.hidden { display: none; }
div { margin: 10px; }
label { width: 100px; display: inline-block; }
.as-console-wrapper { max-height: 65px !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 300px; overflow: hidden;">
  <div>
    <label for="formfield1">Form Field 1</label> <input type="text" id="formfield1" />
  </div>
  <div id="errorMessage" tabindex="1" class="hidden">

  </div>
  <div>
    <label for="formfield2">Form Field 2</label> <input type="text" id="formfield2" />
  </div>

</div>

最佳答案

这为我解决了这个问题:

$('#formfield1').blur(function() {
    window.setTimeout(function () { $('#errorMessage').text('Form field is required').show(); }, 100);
});

不知道为什么,但它有效。仅供引用 - 我尝试将超时设置为 50,但没有成功。

关于javascript - 点击被忽略 : Issue with label elements to associate with form controls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54835984/

相关文章:

jquery - JqG​​rid需要超链接-需要通过Jquery捕获值

html - 如何根据嵌套文本框的内容自动为td分配宽度

javascript - 用 JS 移动 div(已编辑)

java - Jmeter:如何在单个请求中传递数组值?

javascript - navigator.contacts.find 不工作(cordova/phonegap)

javascript - 同步代码

javascript - javascript中的小迭代

javascript - 如何减少 jquery 中按钮的事件监听器数量?

Javascript - 在 Canvas 上方放置一个 html 元素

iphone - 移动 safari 中忽略的溢出 x 值