Home  >  Article  >  Web Front-end  >  How to make a method trigger only once in jquery

How to make a method trigger only once in jquery

WBOY
WBOYOriginal
2021-11-30 10:40:174783browse

在jquery中,可以利用one()函数让方法只触发一次,当使用该函数时,每个元素只能运行一次事件处理方法,语法为“元素对象.one("事件",事件处理方法);”。

How to make a method trigger only once in jquery

本教程操作环境:windows7系统、jquery3.2.1版本、Dell G3电脑。

jquery怎样让方法只触发一次

在jquery中,可以使用one()方法实现让jquery事件只执行一次。下面以点击p标签文字,弹出p标签内容为例,看一下怎么让jquery事件执行一次。示例如下:

1、新建一个html文件,命名为test.html,用于讲解>怎么让jquery事件执行一次。引入jquery.min.js库文件,成功加载该文件,才能使用jquery中的方法。使用p标签创建一行文字,文字内容为“这是一段测试的文字”,并设置其class为mypp。

How to make a method trigger only once in jquery

2、在js标签内,在页面加载完成时,通过class(mypp)获得p元素对象,使用one()方法给对象绑定click点击事件,当p元素被点击时,执行function()方法一次。

在function()方法内,使用$(this)获得p标签对象,使用text()方法取得p标签内的值,把值保存在ny变量中,使用alert()方法将获得的内容输出来。

How to make a method trigger only once in jquery

在浏览器打开test.html文件,点击文字,查看实现的效果。

How to make a method trigger only once in jquery

How to make a method trigger only once in jquery

总结:

1、创建一个test.html文件。

2、在文件内,使用p标签创建一行文字。

3、在js标签内,在页面加载完成时,获得p元素对象,使用one()方法给对象绑定click点击事件,当p元素被点击时,只执行一次function()内代码,再次点击时,不再产生效果。

注意事项:

当使用 one() 方法时,每个元素只能运行一次事件处理器函数。

相关视频教程推荐:jQuery视频教程

The above is the detailed content of How to make a method trigger only once in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn