简体   繁体   English

模糊事件在第一次尝试时不会触发

[英]blur event doesn't trigger at first attempt

I'm trying to update the DOM based on the value entered in a text box. 我正在尝试根据文本框中输入的值更新DOM。

HTML: HTML:

<input id="event-name" type="text"/>

JQUERY: JQUERY:

$('#event-name').on('blur',function(){
  $.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
  //my code here
  });
});

this works on the first blur in Chrome. 这适用于Chrome中的第一个模糊。 When I tried it in opera, mozilla and edge it doesn't worked on the first attempt. 当我在歌剧,mozilla和边缘尝试它时,它在第一次尝试时没有奏效。

It worked when I added this before the jquery. 当我在jquery之前添加它时,它工作。

$("#event-name").focus();
$("#event-name").blur();
$("#event-name").focus();

I did this to make the first $.post call to occur when the page opens. 我这样做是为了在页面打开时进行第一次$ .post调用。

Why is this problem happening? 为什么会出现这个问题? How to solve this in a proper way? 如何以正确的方式解决这个问题? Please help! 请帮忙!

You can try this code: 你可以试试这段代码:

var lazyTriggerEvent = function(id,event,callback){
    var searchTrigger=null;
    $("#"+id).bind(event,function(){
        var text = $.trim($(this).val());
        clearTimeout(searchTrigger);
        searchTrigger = setTimeout(function(){
            callback(text);
        },500);
      })
   };
//use keyup event
lazyTriggerEvent("event-name","keyup",function(){})

It often happens with elements across browsers that consequent events do not work when binding an event to them through ID or class. 跨浏览器的元素经常发生,当通过ID或类将事件绑定到它们时,后续事件不起作用。 The following solution should help you: 以下解决方案应该可以帮助您:

$(document).on('blur','#event-name', function(){
  $.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
  //my code here
  });
});

Alternatively, you could use keyup event. 或者,您可以使用keyup事件。 You can do so following: 你可以这样做:

$(document).on('keyup','#event-name', function(){
  var eventName = $(this).val();
  $.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
  //my code here
  });
});

Also, using - in IDs is not a good approach. 此外,使用-在IDS是不是一个好方法。 Rather, either stick to camelCase or underscore_format of naming convention. 相反,要么坚持使用camelCase ,要么遵循命名约定的underscore_format

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM