当文档已加载以检查选择框的值以及该框发生更改时,我想在初始化阶段进行一些测试并执行一些更改。这是我的操作方式,并且工作正常,但是我想知道是否有更简单的方法,因为我必须通过一个函数来执行它,并在启动时调用它,并且在按钮改变时也调用它。 / p>
// In case this is baseline, project or pre-sales, we will have different text to be selected
function project_type_value_check() {
switch ($("#project_type option:selected").val()){
case "Baseline":
$('#revenue_text').text("MRC (k€)");
$("#revenue").attr("placeholder", "MRC (k€)");
break;
case "Pre-sales":
alert('presales');
break;
default:
$('#revenue_text').text("Revenue (k€)");
$("#revenue").attr("placeholder", "Revenue (k€)");
}
}
// This is when the page loads
project_type_value_check();
// This is when the select box changes
$('#project_type').change(function() {
project_type_value_check();
});
答案 0 :(得分:0)
我认为这更优雅
var vals = {"Baseline":"MRC (k€)","Pre-sales":"Presales"}
$(function() {
$('#project_type').on("change",function() {
var val = this.value || "Baseline"
var show = vals[val]
if (val=="Pre-sales") alert(show);
else {
$('#revenue_text').text(show);
$("#revenue").attr("placeholder", show);
}
}).trigger("change");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="project_type">
<option value="">Please select</option>
<option value="Baseline">Baseline</option>
<option value="Pre-sales">Pre-sales</option>
</select><br/>
<span id="revenue_text"></span>
<input type="text" id="revenue" value=""/>