Javascript , event handler is always called, even if the event is not raised(Javascript ,事件处理程序总是被调用,即使事件没有被引发)
问题描述
我有以下代码扩展了 JQuery 并向 JQuery 添加了一个方法:
i have the following code which extends the JQuery and adds a method to the JQuery:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage());
}
function showMessage() {
alert('hi');
}
所以我可以按如下方式使用该代码:
so I can use that code as follows :
<input type="text" name="name" id="textbox" />
$(document).ready(function () {
$("#textbox").attachWithMessage ();
});
当我第一次加载页面时,会出现一个带有 ('hi') 消息的消息框.
when I load the page for the first time, a message box shows up with ('hi') message.
即使我没有点击文本框.
even if I didn't click in the text box.
我也尝试了点击事件,消息仍然自动显示.
I also tried the click event, and the message still shows automatically.
有什么想法吗??
推荐答案
这里的问题是,当你将 showMessage()
作为参数传递给 focusin
时,函数showMessage
被执行,返回值被传递给focusin
.
The issue here is that when you pass showMessage()
as a parameter to focusin
, the function showMessage
is executed and the return value is passed to focusin
.
相反,您需要传递对函数的引用(不带括号).
Instead you need to pass a reference to the function (without the paranthesis).
使用以下代码进行扩展:
Use the following code to extend:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage);
}
工作示例@ http://jsfiddle.net/eXEP5/
如果您想将参数传递给 showMessage,请尝试以下操作:
If you want to pass a parameter to showMessage then try this:
$.fn.attachWithMessage = function () {
var param1 = "Some Param";
$(this).focusin(function(){
showMessage(param1); //Make sure showMessage is modified accordingly for the parameters.
});
}
这篇关于Javascript ,事件处理程序总是被调用,即使事件没有被引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript ,事件处理程序总是被调用,即使事件没有被引发


基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01