我尝试对所有控件使用相同的验证函数。但我对 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, 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);
}
}
$(document).ready(function(){
$("#txtFirstName").bind('focusout', function() {
validate(this, "defaultValue here", "Error message here", "Valid message here");
});
});
如果您有疑问,请提出:)
<小时/>绑定(bind)事件处理程序的第一个参数是事件对象本身。请参阅 .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, defaultInputValue, ErrorMessage, ValidMessage)
但是如果您描述了您实际遇到的错误,那就更好了。
<小时/>第二个问题:如果我没看错的话,第二个绑定(bind)在某种程度上没有上下文:
$(document).ready(function(){
$("#txtFirstName").bind('focusout', function(){});
$(this).bind('customblurfocus',function(defaultInputValue,ErrorMessage,ValidMessage)
{ //...
});
});
您要将自定义事件绑定(bind)到哪个元素? $(this)
应该是什么?在这种状态下,即使添加 event
作为函数的第一个参数,这也不起作用。
请告诉我们更多有关您的 HTML 结构和/或您想要实现的目标的信息。
关于jquery - 如何在Jquery中使用触发器传递参数数据以及控制(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2596387/