微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Jquery中使用触发器传递参数数据以及控制(this)

我试图为我的所有控件使用相同的验证功能.但我在jQuery中不太了解,也无法将事件处理程序传递给触发器.我想将文本框ID传递给我的自定义函数.
我怎样才能做到这一点
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    $("#txtFirstName").bind('focusout',function()
   {
   $(this).trigger("customblurfocus",[$(this).val(),$(this).val() + " required !","Ok !"]);
   }
  );

  $(this).bind('customblurfocus',function(defaultInputValue,ErrorMessage,ValidMessage)
     {alert($(this).val()); 
     if($(this).val()=="" || $(this).val()==defaultInputValue)
      {
      $(this).val(defaultInputValue);
      $(this).siblings("span[id*='error']").toggleClass("error_set").text(ErrorMessage).fadeOut(3000);  
      }
     else
      {
      $(this).siblings("span[id*='error']").toggleClass("error_ok").text(ValidMessage).show(1000);
      }
     }
   );
    });
</script>

解决方法

更新:我想我想出了你想要实现的目标,这应该有效(自定义事件不需要):
function validate(element,defaultInputValue,ValidMessage) {
    alert($(this).val()); 
    if($(this).val()=="" || $(this).val()==defaultInputValue)
    {
        $(this).val(defaultInputValue);
        $(this).siblings("span[id*='error']").toggleClass("error_set").text(ErrorMessage).fadeOut(3000);  
    }
    else
    {
       $(this).siblings("span[id*='error']").toggleClass("error_ok").text(ValidMessage).show(1000);
    }
}

$(document).ready(function(){
   $("#txtFirstName").bind('focusout',function() {
      validate(this,"defaultValue here","Error message here","Valid message here");
   });
});

如果您有疑问,请问:)

绑定事件处理程序的第一个参数是事件对象本身.请参阅.trigger() documentation中的示例:

$('#foo').bind('custom',function(event,param1,param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom',['Custom','Event']);

和:

The event object is always passed as the first parameter to an event handler,but if additional parameters are specified during a .trigger() call as they are here,these parameters will be passed along to the handler as well.

所以你的看起来应该是这样的:

function(event,ValidMessage)

但如果你描述了你实际得到的错误会更好.

第二个问题:如果我看到第二个绑定在某种程度上没有上下文:

$(document).ready(function(){
     $("#txtFirstName").bind('focusout',function(){});

     $(this).bind('customblurfocus',ValidMessage)
     { //...
     });
});

要将哪个元素绑定到自定义事件? $(这)应该是什么?在这种状态下,即使将event添加函数的第一个参数,这也不起作用.请告诉我们有关您的HTML结构和/或您想要实现的内容的更多信息.

原文地址:https://www.jb51.cc/jquery/241406.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐