doubingjiu3199
2016-09-04 08:20
浏览 78

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

I'm trying to update the DOM based on the value entered in a text box.

HTML:

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

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. When I tried it in opera, mozilla and edge it doesn't worked on the first attempt.

It worked when I added this before the 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.

Why is this problem happening? How to solve this in a proper way? Please help!

图片转代码服务由CSDN问答提供 功能建议

我正在尝试根据文本框中输入的值更新DOM。

HTML:

 &lt; input id =“event-name”type =“text”/&gt; 
   \  n 
 

JQUERY:

  $('#event-name')。on('blur',function(){
 $ .post(“scripts)  /add-team-support.php",{eventName:eventName},function(minAndMaxString){
 //我的代码在这里
}); 
}); 
   
  
 

这适用于Chrome中的第一个模糊。 当我在opera,mozilla和edge中尝试它时,它在第一次尝试时不起作用。

当我在jquery之前添加它时它起作用了。 < 预> <代码> $( “#事件名称”)聚焦(); $的( “#事件名称”)模糊(); $的( “#事件名称”)聚焦() ;

我这样做是为了在页面打开时进行第一次$ .post调用。

为什么这样 问题发生了什么? 如何以正确的方式解决这个问题? 请帮助!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhe1264 2016-09-04 08:44
    已采纳

    It often happens with elements across browsers that consequent events do not work when binding an event to them through ID or class. 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. 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. Rather, either stick to camelCase or underscore_format of naming convention.

    点赞 评论
  • douzhangshao6369 2016-09-04 08:29

    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(){})
    
    点赞 评论

相关推荐 更多相似问题