我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TEST</title>
</head>
<body>
How can I get the code to fire on load, maintaining the change/keypress?<br/>
<select id="textFieldId" name="textFieldId">
<option value="1">End Date</option>
<option value="2">End Date Plus 30</option>
<option value="3">End Date Plus Custom</option>
<option value="4">Print Date Plus Custom</option>
<option value="5">Static Expiration Date (New)</option>
</select>
<pre id="ONE">If user selects 1</pre>
<pre id="TWO">If user selects 2</pre>
<pre id="THREE">If user selects 3</pre>
<pre id="FOUR">If user selects 4</pre>
<pre id="FIVE">If user selects 5</pre>
</body>
</html>
$(document).ready(function(){
$("#textFieldId").val("3").change();
$("#textFieldId").on("change keyup", function(){
var selectedVal = $(this).val();
$("pre").hide();
if(selectedVal == "1"){
$("pre#ONE").show();
}
else if(selectedVal == "2"){
$("pre#TWO").show();
}
else if(selectedVal == "3"){
$("pre#THREE").show();
}
else if(selectedVal == "4"){
$("pre#FOUR").show();
}
else{
$("pre#FIVE").show();
}
return false;
});
});
我的问题是,如果jQuery中有一个内置函数,它不仅可以设置列表的选定值,还可以激活它所绑定的函数。
我有一个解决方法,即在自己的函数中删除show / hide图层并在更改/ keyup和初始加载时触发它。
这是最好的方法吗?
答案 0 :(得分:0)
你可以切换到调用绑定它的函数
$(document).ready(function(){
$("#textFieldId").val("3").change();
$("#textFieldId").on("change keyup", myFunction);
});
function myFunction(){
var selectedVal = $(this).val();
$("pre").hide();
$("#id" + selectedVal).show();
switch(selectedVal){
case "1":
//call a function
break;
case "2":
//call a function
break;
}
return false;
}
HTML - 稍微修改了pre
id
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TEST</title>
</head>
<body>
How can I get the code to fire on load, maintaining the change/keypress?<br/>
<select id="textFieldId" name="textFieldId">
<option value="1">End Date</option>
<option value="2">End Date Plus 30</option>
<option value="3">End Date Plus Custom</option>
<option value="4">Print Date Plus Custom</option>
<option value="5">Static Expiration Date (New)</option>
</select>
<pre id="id1">If user selects 1</pre>
<pre id="id2">If user selects 2</pre>
<pre id="id3">If user selects 3</pre>
<pre id="id4">If user selects 4</pre>
<pre id="id5">If user selects 5</pre>
</body>
</html>
答案 1 :(得分:0)
尝试使用较少的代码JSFIDDLE
$(document).ready(function(){
// INITIAL LOAD OF SCREEN - PRELOAD DATA
myFunction("4");
// SUBSEQUENT ACTIO NFROM USER
$("#textFieldId").on("change keyup", function(){
myFunction($(this).val());
return false;
});
});
function myFunction(i){
var selectedVal = i;
$("pre").hide();
var temp = '#id'+selectedVal
$(temp).show();
}