有没有办法简化和组合这两个功能?我为大量元素做这件事,很快变得太麻烦。
我已在此处上传了代码的实际示例:http://jsfiddle.net/JFJSA/5/
$(document).ready(function () {
var goalVal = $("[name=objective]").val();
$("#goal_Minimize, #goal_Maximize, #AltScenario").hide();
if (goalVal === "Minimize") {
$("#goal_Minimize").show();
} else if (goalVal == "Maximize") {
$("#goal_Maximize").show()
} else if (goalVal == "AltScenario") {
$("#AltScenario").show()
};
});
$("[name=objective]").change(function () {
var goalVal = $("[name=objective]").val();
$("#goal_Minimize, #goal_Maximize, #AltScenario").hide();
if (goalVal == "Minimize") {
$("#goal_Minimize").show();
} else if (goalVal == "Maximize") {
$("#goal_Maximize").show()
} else if (goalVal == "AltScenario") {
$("#AltScenario").show()
};
});
答案 0 :(得分:1)
是的,只需用正常的函数替换你的匿名函数:
var doTheThing = function() {
var goalVal = $("[name=objective]").val();
$("#goal_Minimize, #goal_Maximize, #AltScenario").hide();
if (goalVal === "Minimize") {
$("#goal_Minimize").show();
} else if (goalVal == "Maximize") {
$("#goal_Maximize").show()
} else if (goalVal == "AltScenario") {
$("#AltScenario").show()
};
};
$(document).ready(doTheThing);
$("[name=objective]").change(doTheThing);