当页面加载时和当按钮被点击时,Jquery运行

编程入门 行业动态 更新时间:2024-10-25 17:30:07
本文介绍了当页面加载时和当按钮被点击时,Jquery运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果一个人去我的页面,我想要一些jQuery运行,然后如果他们单击页面上的按钮,我想要运行相同的jquery代码。我必须为此创建单独的函数吗?一个人加载时,人到达的页面,然后点击功能,当有人点击按钮?

解决方案

您可以重复使用这两个函数:

$(function(){ //声明函数 function myReusableFunction (){ // do something extraordinary } //在页面加载时调用 myReusableFunction(); 分配给处理程序 $('button')。click(myReusableFunction); });

请注意, this

如果这是一个问题,你可以直接通过链接一个点击 trigger。

$(function(){ //分配给处理程序并调用 $('button')。click(function(){ // do something extraordinary })。

EDIT:有多个按钮分配给它, .click()将触发全部。

如果这不是您想要的,您可以将其更改为:

p $ p> $(function(){ //分配给处理程序并调用 $('button' b $ b // do something extraordinary })。eq(0).click(); });

...仅在第一个触发。

或:

$(function(){ // assign到处理程序并调用 $('button')。click(function(){ // do something extraordinary })triggerHandler('click'); } );

...只有第一个元素触发,但也有一些其他差异。有关详情,请参阅 triggerHandler 的文档。

If a person went to my page I want some jquery to run, then if they click a button on the page I want the same jquery code to run. Do I have to create seperate functions for this? One that loads when the person comes to the page and then the click function when someone clicks the button? Or for the sake of not having to duplicate code can it all be in one function?

解决方案

You can reuse the function for both:

$(function() { // declare the function function myReusableFunction() { // do something extraordinary } // call it on page load myReusableFunction(); // assign to handler $('button').click( myReusableFunction ); });

Note that the value of this and the parameter (if any) will be different.

If that's an issue, you can just call it directly by chaining a click trigger.

$(function() { // assign to handler AND call it $('button').click( function() { // do something extraordinary }).click(); });

EDIT: If there's more than one button that it is assigned to, the .click() will trigger for all of them.

If this isn't what is desired, you could change it to:

$(function() { // assign to handler AND call it $('button').click( function() { // do something extraordinary }).eq(0).click(); });

...to trigger it only on the first one.

Or this:

$(function() { // assign to handler AND call it $('button').click( function() { // do something extraordinary }).triggerHandler( 'click' ); });

...which only fires on the first element, but also has a couple other differences. See the docs for triggerHandler for more.

更多推荐

当页面加载时和当按钮被点击时,Jquery运行

本文发布于:2023-06-09 04:13:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/595005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   加载   页面   Jquery

发布评论

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

>www.elefans.com

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