使用 select2 的动态 select 选项不起作用
Dynamic select option using select2 not working
在我的页面中,我有一个使用 select2 的 select 选项和一个用于向页面动态添加新 select 选项的按钮。但是我对由按钮动态创建的新控件有疑问,我不能再像原始控件那样 select 它了。我仍在努力解决它,但如果你能帮助我,那就太好了,在此先感谢!
<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>
这里是my fiddle
更好的解决方案是先克隆第一个元素,然后在每次追加之后重新启动 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();
} );
在我的页面中,我有一个使用 select2 的 select 选项和一个用于向页面动态添加新 select 选项的按钮。但是我对由按钮动态创建的新控件有疑问,我不能再像原始控件那样 select 它了。我仍在努力解决它,但如果你能帮助我,那就太好了,在此先感谢!
<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>
这里是my fiddle
更好的解决方案是先克隆第一个元素,然后在每次追加之后重新启动 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();
} );