即使未引发事件,也始终调用Javascript,事件处理程序

编程入门 行业动态 更新时间:2024-10-19 08:43:38
本文介绍了即使未引发事件,也始终调用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.

相反,你需要传递对函数的引用(没有paranthesis)。

Instead you need to pass a reference to the function (without the paranthesis).

使用以下代码extend:

Use the following code to extend:

$.fn.attachWithMessage = function () { $(this).focusin(showMessage); }

工作示例@ jsfiddle/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,事件处理程序

本文发布于:2023-11-13 00:23:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   程序   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!