有人可以帮助您了解如何将条件添加到以下代码段吗?
段:
function editStudesnt(data) {
$('#studentInfo').empty();
$('#studentInfo').append("<div id=\"Search\" class=\"results\">"+
"<span id=\"lb\">Student Name:"+data.stuName+"</span></div>"+
"<label>Student Id: </label>"+
"<span id=\"SID\">"+data.stuId +"</span><br />");
}
如果需要条件
,如何在上述代码段中添加if条件例如,
if(data.courseId==1){
<label>Student Course: </label> <select id=\"courseId\"><option value="" selected="selected">Mechanical</option><option value=\"1\" selected="\selected\">Mechanical</option><option value=\"2\">Computer Science</option><option value=\"2\">Electronics</option></select>"
}
if(data.courseId==2){
<label>Student Course: </label> <select id=\"courseId\"><option value="" selected="selected">Mechanical</option><option value=\"1\" >Mechanical</option><option value=\"2\" selected="\selected\">Computer Science</option><option value=\"2\">Electronics</option></select>"
}
上面的代码工作正常。但问题是,当我有更多课程时,相同的代码会在每种情况下重复出现。所以任何人都可以请我提供一个解决方案,我可以在选项中写出if条件,例如MechanicalComputer Science。
答案 0 :(得分:0)
just add below in function
function editStudesnt(data) {
$('#studentInfo').empty();
$('#studentInfo').append("<div id=\"Search\" class=\"results\">"+
"<span id=\"lb\">Student Name:"+data.stuName+"</span></div>"+
"<label>Student Id: </label>"+
"<span id=\"SID\">"+data.stuId +"</span><br />");
if(data.courseId==1){
$('#studentInfo').append("<label>Student Course: </label> <select id=\"courseId\"><option value="" selected="selected">Mechanical</option><option value=\"1\" selected="\selected\">Mechanical</option><option value=\"2\">Computer Science</option><option value=\"2\">Electronics</option></select>");
}
if(data.courseId==2){
$('#studentInfo').append("<label>Student Course: </label> <select id=\"courseId\"><option value="" selected="selected">Mechanical</option><option value=\"1\" >Mechanical</option><option value=\"2\" selected="\selected\">Computer Science</option><option value=\"2\">Electronics</option></select>")
}
}
想要这样做吗?
答案 1 :(得分:0)
将控件构建为控件会更清晰,所以
var select = $("<select></select");
var option = $("<option></option>");
option.text("hello")
option.val("2");
if(data.val == option.val()) option.attr("selected", "selected");
select.append(option);