请看一下这个片段:
$("document").ready(function () {
$("#eth0_mode").change(function () {
$("#group").find(":input").prop("disabled", this.value === "dhcp");
$("#group").collapse(this.value === "dhcp" ? "hide" : "show");
});
$("#eth0_mode").val("dhcp").trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<form>
<select class="form-control" id="eth0_mode">
<option value="dhcp">DHCP</option>
<option value="fallback">DHCP with fallback</option>
<option value="static">Static address</option>
</select>
<div id="group">
<input class="form-control" type="text" placeholder="address">
</div>
</form>
在页面加载时,它将select的值设置为“dhcp”并触发change事件。 执行该事件是因为将禁用输入字段。但是div没有崩溃!
但如果您选择另一个项目并返回“dhcp”,则div将崩溃。
为什么?
答案 0 :(得分:1)
您需要将collapse
类添加到#group
元素才能使其正常工作:
$("document").ready(function () {
$("#eth0_mode").change(function () {
$("#group").find(":input").prop("disabled", this.value === "dhcp");
$("#group").collapse(this.value === "dhcp" ? "hide" : "show");
});
$("#eth0_mode").val("dhcp").trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<form>
<select class="form-control" id="eth0_mode">
<option value="dhcp">DHCP</option>
<option value="fallback">DHCP with fallback</option>
<option value="static">Static address</option>
</select>
<div id="group" class="collapse show">
<input class="form-control" type="text" placeholder="address">
</div>
</form>