当页面加载时和当按钮被点击时,Jquery运行 [英] Jquery running when page loads and when button clicked
问题描述
如果一个人去我的页面,我想要一些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运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!