如果一个人去我的页面,我想要一些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运行
发布评论