由于"失焦(blur)"事件,导致"点击(click)"事件无法触发。

8
为了重现此问题,请使用[1]中的fiddle并按照以下步骤操作:
  1. 点击文本框

  2. 在文本框中输入一些值

  3. 在输入值后,点击“click me”按钮。请注意,不要在浏览器上其他地方单击。

  4. 您会发现“button click”事件未被触发。

HTML代码如下:
   <div class="wrapper">
    <input type="text" id="input"/>
    <div class="error">There is an error </div>
    </div>
    <button type="button" id="button">Click Me</button>
    <div id="log">Logs</div>

同样的JavaScript代码如下:
$(function () {
   $("input,button").on("click focus blur mousedown mouseup", function (e) {
     $("#log").append($("<div/>").html(e.target.id + " " + e.type))
     var self = this     
     if (self.id === "input" && e.type=="blur") {
       $(self).trigger("exit")
     }      
   })
   $(".wrapper").on("exit", function () {         
      $(this).find(".error").hide()
      $(this).find(".error").text("")
   })
})

该问题在“Chrome”和“Firefox”中都能重现。这是“Chrome”中已知的错误还是其他人遇到过类似的问题?理想情况下,按钮上的单击事件应该被触发,但不知何故没有触发?我无法理解原因或可能的修复方法。我不想使用setTimeout()来推迟“blur”事件的执行。
[1] https://jsfiddle.net/cg1j70vb/1/

这仅在第一次发生。 - Sandeep Nayak
是的,我确实注意到了...当您删除错误文本时,可能会进行DOM重新绘制。 - Sandeep Nayak
有没有办法可以保持按钮的移动同时仍然保留点击事件?我不想增加按钮的高度。 - Rishi Mehta
您可以在错误文本上使用visibility:hidden属性。这不会使按钮上移。 - Sandeep Nayak
是的,那样做可以,但我的用例还包括动态更改错误文本的HTML内容? - Rishi Mehta
显示剩余2条评论
2个回答

3
自从在输入框的失去焦点事件中删除了错误文本,就会出现这种情况。这将导致按钮向上移动(可能是DOM重新渲染),因此会错过单击操作。
我删除了错误消息,现在可以正常工作了。

$(function() {
  $("input,button").on("click focus blur mousedown mouseup", function(e) {
    $("#log").append($("<div/>").html(e.target.id + " " + e.type))
    if (this.id === "input" && e.type == "blur") {
      $(this).trigger("exit")
    }
  })
  $(".wrapper").on("exit", function() {
    $(this).find(".error").hide()
    $(this).find(".error").text("")
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <input type="text" id="input" />

</div>
<button type="button" id="button">Click Me</button>
<div id="log">Logs</div>


我同意你的观点,hide()函数导致按钮在点击事件同时发生了移动。 - rachmatsasongko
1
是的,这是因为按钮的移动。感谢您的回答。 - Rishi Mehta

0

我认为是你的错误消息的hide()函数导致了问题。

我尝试将其删除,只替换错误消息,这样就解决了。 演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接