jQuery - Multiple Triggers for the Same Function
I'm developing some jQuery, but I'm a beginner so it's a little bit bloated and not very elegant. Basically, I want a cookie value to be nullified when either one of two forms are submitted or their submit buttons are clicked. But I don't know how to consolidate the conditions of the function so that I only have to write out the function once, so the best I can do is this:
$('form#searchform-basic').submit(function() {
$.cookie('tab_cookie', null);
});
$('form#searchform-basic a.search').click(function() {
$.cookie('tab_cookie', null);
});
$('form#searchform-advanced').su开发者_开发技巧bmit(function() {
$.cookie('tab_cookie', null);
});
$('form#searchform-advanced input#search-button-submit').click(function() {
$.cookie('tab_cookie', null);
});
There's got to be a better way, right?
And before anybody asks, yes, you would think that you'd only need to know when the forms are being submitted. But leaving out the click events means that the function doesn't run when the submit buttons are clicked. I don't know why it is like that, it just is.
Give your function a name, like so:
function ClearCookie() {
$.cookie('tab_cookie', null);
}
That way, you can call it from multiple events as needed.
$('form#searchform-basic').submit(ClearCookie);
$('form#searchform-basic a.search').click(ClearCookie);
$('form#searchform-advanced').submit(ClearCookie);
$('form#searchform-advanced input#search-button-submit').click(ClearCookie);
Voila!
To take it one step further, you can combine the selectors that are calling the same event (submit or click), like so:
$('form#searchform-basic, form#searchform-advanced').submit(ClearCookie);
$('form#searchform-basic a.search, form#searchform-advanced input#search-button-submit').click(ClearCookie);
I would probably leave off the form tag and just use the IDs, but that is just me.
$('#searchform-basic, #searchform-advanced').submit(ClearCookie);
$('#searchform-basic a.search, #searchform-advanced input#search-button-submit').click(ClearCookie);
$('oneselector','second','third').click(function() {
$.cookie('tab_cookie', null);
});
try that
Well since clicking the submit button actually submits the form, you don't need to bind a click handler whatsoever to the submit button, just bind your control to the submit action of the form (which happens as a consequence of clicking a submit button).
To simplify it into one line, add a class to your forms such as clear-cookie
.
<form id="searchform-basic" class="clear-cookie"> ... </form>
<form id="searchform-advanced" class="clear-cookie"> ... </form>
$("form.clear-cookie").submit(function(){
$.cookie('tab_cookie', null);
});
More to the point of multiple selectors however, you can, as mentioned above do something like:
$("#searchform-basic, #searchform-advanced").submit( ... );
But I find that I usually group related elements using classes.
精彩评论