我有一个包含两个列表框的网页。我的jQuery / JavaScript有问题。当用户在左侧列表框中选择一个项目时,应在右侧列表框中选择三个项目。除非我刷新页面,否则它只能在第一次使用。我知道代码正在执行,因为我可以逐步执行它。这似乎是一个简单的任务,所以我必须缺少一些东西。我在www.tutorialspoint.com上创建了该问题的在线示例,其中显示了该问题。 Listbox sample online-按“预览”按钮。谢谢您的帮助!
<!DOCTYPE html>
<html>
<head>
<title>Re-select Items in Listbox</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#meters').change(function () {
$('#baselines option').prop('selected', false); // Clear selected baselines
var data = [2, 3, 4];
var len = $('#baselines option').length;
for (var i = 1; i <= len; i++) {
$("#baselines option[value=" + i + "]").attr("selected", (data.indexOf(i) !== -1) ? true : false);
}
});
});
</script>
</head>
<body>
<p id="myid">Is is a test of selecting items in listbox</p>
<div>
<select class="form-control" id="meters" name="SelectedMeters" style="width: 200px;">
<option value="1">12345678</option>
<option value="2">1234567890</option>
</select>
<select class="form-control" id="baselines" multiple="True" name="SelectedBaselines" size="10" style="width: 200px;">
<option value="1">MeterBaseline1</option>
<option value="2">MeterBaseline2</option>
<option value="3">MeterBaseline3</option>
<option value="4">MeterBaseline4</option>
<option value="5">MeterBaseline5</option>
<option value="6">MeterBaseline6</option>
<option value="7">PJM_MovingAvg</option>
</select>
</div>
</body>
</html>
答案 0 :(得分:2)
使用removeAttr取消选择选项,然后选择prop
<!DOCTYPE html>
<html>
<head>
<title>Try jQuery Online</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
$(document).ready(function() {
$("em").addClass("selected");
$("#myid").addClass("highlight");
$('#meters').change(function () {
$('#baselines option').removeAttr('selected');
var data = [getRndInteger(1, 2),getRndInteger(3, 4),getRndInteger(5, 7)];
console.debug(data);
var len = $('#baselines option').length;
for (var i = 1; i <= len; i++) {
$("#baselines option[value=" + i + "]").prop("selected", (data.indexOf(i) !== -1) ? true : false);
}
});
});
</script>
<style>
.selected {
color:red;
}
.highlight {
background:yellow;
}
</style>
</head>
<body>
<p id="myid">Is is a test of selecting items in listbox</p>
<div>
<select class="form-control" id="meters" name="SelectedMeters" style="width: 200px;">
<option value="1">12345678</option>
<option value="2">1234567890</option>
</select>
<select class="form-control" id="baselines" multiple="True" name="SelectedBaselines" size="10" style="width: 200px;">
<option value="1">MeterBaseline1</option>
<option value="2">MeterBaseline2</option>
<option value="3">MeterBaseline3</option>
<option value="4">MeterBaseline4</option>
<option value="5">MeterBaseline5</option>
<option value="6">MeterBaseline6</option>
<option value="7">PJM_MovingAvg</option>
</select>
</div>
</body>
</html>
答案 1 :(得分:1)