我正在使用在select元素中选择的jQuery以使其更加用户友好,但是当我使用jquery将选择的div复制到另一个div时,它不起作用
$(document).ready(function() {
$(".chosen").chosen({});
$("#movechosen").click(function() {
var chosenHtml = $(".mycontainer").html();
$(".movecontainer").append(chosenHtml);
});
});
<div class="mycontainer" style="background:#ddd">
Container 1: <select class="chosen" multiple>
<option>Select option</option>
<option>USA</option>
<option>Germany</option>
<option>India</option>
<option>China</option>
<option>Canada</option>
<option>Australia</option>
</select>
</div>
<div class="movecontainer" style="background:#e1e1e1">
Container 2 :
</div>
<input type="button" value="copy to container 2" id="movechosen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.css" />
它正在复制到另一个容器,但是当您专注于所选容器时,它将不会加载其中的可用元素。
最佳答案
克隆元素时销毁插件,然后在追加之后重新初始化它们:
尝试以下方法:
$(document).ready(function() {
$(".chosen").chosen();
$("#movechosen").click(function() {
$(".chosen").chosen("destroy");
var chosenHtml = $(".mycontainer").html();
$(".movecontainer").append(chosenHtml);
$(".chosen").chosen();
});
});
<div class="mycontainer" style="background:#ddd">
Container 1: <select class="chosen" multiple>
<option>Select option</option>
<option>USA</option>
<option>Germany</option>
<option>India</option>
<option>China</option>
<option>Canada</option>
<option>Australia</option>
</select>
</div>
<div class="movecontainer" style="background:#e1e1e1">
Container 2 :
</div>
<input type="button" value="copy to container 2" id="movechosen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.1/chosen.css" />