我正在使用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" />
它正在复制到另一个容器,但是当你专注于选择它时,它将不会加载其中可用的元素。
答案 0 :(得分:2)
克隆元素时销毁插件,然后在追加后重新初始化它们:
尝试以下方法:
$(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" />