$('a#noday').click(function()
{ for(g=1;g<=10;g++)
var ddl = document.getElementById('daySelect_'+g);
var opts = ddl.options.length;
for (var i=0; i<opts; i++){
if (ddl.options[i].value == ""){
ddl.options[i].selected = true;
break;
}
})
$('a#wed').click(function()
{ for(g=1;g<=10;g++)
var ddl = document.getElementById('daySelect_'+g);
var opts = ddl.options.length;
for (var i=0; i<opts; i++){
if (ddl.options[i].value == "wed"){
ddl.options[i].selected = true;
break;
}
})
以下是我选择的html代码
<select class="form-control daySelect" id="daySelect_1" name="daySelect_1">
<option value="">Select</option>
<option value="wed">Wed</option>
<option value="sat">Sat</option>
<option value="sun">Sun</option>
<option value="satsun">Sat/Sun</option>
<option value="wedsatsun">WedSatSun</option>
</select>
以下是我的超链接html
Set all to:
<a id="noday" href="#"><span class="label label-info">No Day</span></a>
<a id="wed" href="#"><span class="label label-info">Wednesday</span></a>
我尝试点击超链接,但我选择的下拉列表不会更改。我确实尝试了警报,以确保我的链接正常工作,并设法执行警报。
我的JsFiddle
答案 0 :(得分:2)
一些事情。你缺少很多大括号,你会注意到你的控制台有错误。您还假设存在daySelect_
1到10,根据您的小提琴他们可能不存在。
$('a#noday').click(function() {
for (g = 1; g <= 10; g++) { // This was missing
var ddl = document.getElementById('daySelect_' + g);
if (!ddl) continue; // What if there is no daySelect_10?
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == "") {
ddl.options[i].selected = true;
break;
}
} // Missing this brace too
}
});
$('a#wed').click(function() {
for (g = 1; g <= 10; g++) {
var ddl = document.getElementById('daySelect_' + g);
if (!ddl) continue;
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == "wed") {
ddl.options[i].selected = true;
break;
}
}
}
});
最后,您可能想要考虑将jQuery用于所有这些,而不仅仅是DOM事件。它将节省您必须执行许多嵌套for循环,例如:
$('a#noday').click(function() {
$("[id^=daySelect_").val("");
});
$('a#wed').click(function() {
$("[id^=daySelect_").val("wed");
});
更整洁! jsFiddle
答案 1 :(得分:1)
为什么要编写 for 循环,同样可以通过单行语句实现:)
$("#daySelect_1").val("wed");