我很了解 HTML,正在尝试学习 JQuery。我在 JQuery site 上找到了 .change 函数这正是我想要的。
理想情况下,我希望 test1 和 test2 仅相互影响,而 test3 和 test4 仅相互影响,依此类推。
现在 test2 和 test4 影响 test1 和 test3
这是我的代码:
<select id="test1" name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div id="test2"></div>
<script>
$("select#test1").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div#test2").text(str);
})
.change();
</script>
<select id="test3" name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div id="test4"></div>
<script>
$("select#test3").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div#test4").text(str);
})
.change();
</script>
我尝试将它与 ID 分开,但还不够。 我怎样才能让它正常工作?
最佳答案
这一行:
$("select option:selected").each(function () {
应该这样写:
$("#test1 option:selected").each(function() {
通过在该行中使用通用的“select”,您将选择页面上的每个“select”元素,通过使用它的 id,它只会定位所需的选择标签。
关于javascript - 与 JQuery .change 标签斗争的初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16728926/