在我的页面中,我有一个选择选项使用select2和一个按钮来动态添加新的选择选项到页面。但我有一个由按钮动态创建的新控件的问题,我不能再像原始控件那样选择它了。我还在努力解决这个问题,但如果你帮我一把,那就太好了,谢谢你们!
<html>
<head>
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
jQuery( function( $ )
{
var $body = $( 'body' );
$( '.sl-select' ).select2();
$body.on( 'click', '.add-report', function()
{
var $this = $( this ),
$clone = $this.siblings( '.report:last' ).clone();
$clone.insertBefore( $this );
} );
} );
</script>
</head>
<body>
<div class="report">
<select class="sl-select">
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
</div>
<button class="add-report">Add Report</button>
</body>
</html>
答案 0 :(得分:1)
更好的解决方案是先克隆第一个元素,然后在每次追加后重新启动select2插件
var $body = $( 'body' );
var $clone = '<div class="report"><select class="sl-select"><option value="1">option 1</option><option value="2">option 2</option><option value="3">option 3</option></select></div>'
$( '.sl-select' ).select2();
$body.on( 'click', '.add-report', function()
{
var $this = $( this );
$body.prepend($clone);
$( '.sl-select:first').select2();
} );