jquery click(function) onload
I need help to consolidate/minify the code below. Originally I had a dropdown which controls div's visibility based on value. It works onClick but since it's a database page, it doesn't work onLoad so I had to add a 2nd logic. Any suggestions/input is gre开发者_如何学Catly appreciated.
$(document).ready(function () {
var $caseStatus = $(this).find("#auth_status").val();
//alert ($caseStatus);
if ($caseStatus === "1") {
$(".pendingClass").show();
$(".authClass").hide();
}
else if ($caseStatus === "2") {
$(".pendingClass").hide();
$(".authClass").show();
}
else {
$(".pendingClass").hide();
$(".authClass").hide();
}
// Show/Hide Divs for Authorization Status
$("#auth_status").click(function () {
if ($(this).val() === "0") {
$(".pendingClass").hide();
$(".authClass").hide();
}
else if ($(this).val() === "1") {
$(".pendingClass").show();
$(".authClass").hide();
}
else if ($(this).val() === "2") {
$(".pendingClass").hide();
$(".authClass").show();
}
});
});
You could reduce your code a bit by simplifying your if
/else
structure(since anything besides "1"
is the same show/hide result and also just call the handler you're binding when the page first loads, like this:
$(function () {
$("#auth_status").click(function () {
var val = $(this).val();
$(".pendingClass").toggle(val === "1");
$(".authClass").toggle(val === "2");
}).click();
});
$(function () {
function toggleElements() {
var caseStatus = $("#auth_status").val();
$(".pendingClass").toggle(caseStatus === "1");
$(".authClass").toggle(caseStatus === "2");
};
toggleElements(); // initial call (on page load)
$("#auth_status").click(toggleElements); // manual call (on user click)
});
You could define a couple of objects:
var authCtrl = {
'0': { show: null, hide: '.pendingClass, .authClass' },
'1': { show: '.pendingClass', hide: '.authClass' },
'2': { show: '.authClass', hide: '.pendingClass' }
};
and similarly (backwards) for the other case. Then the handler just grabs the entry based on that field value and hides/shows as directed.
精彩评论