动态创建选择输入字段

时间:2018-06-25 14:39:43

标签: javascript jquery web web-deployment materialize

在尝试使用jQuery动态创建Materialize选择输入字段时遇到问题。我的目标是在单击按钮时在div后面附加一个选择字段。这是我当前的代码:

$(document).ready(function(){
  $('select').formSelect();
});

$("#addSelect").click(function(){
   $("#addSelect").addClass("disabled");
   $("#addSelect").hide();    
   $("#newContent").append("<div class='row'><div class='input-field col s12'><select> <option value='' disabled selected>Choose your option</option><option value='1'>Option 1</option><option value='2'>Option 2</option><option value='3'>Option 3</option> </select><label>Materialize Select</label><label>Materialize Select</label></div></div><button class='waves-effect waves-light bg-blue btn right' type='button'>Go</button>");  
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<div class="container">
<div id='newContent'></div>
<br>
<button class="waves-effect waves-light bg-blue btn right" id="addSelect">Add Select</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> 

当我检查元素时,它将为选择添加所有html,但是选择不起作用。也许是CSS问题?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

问题在于,在将动态添加的选择框附加到DOM之前,您正在运行$("select").formSelect()函数。

可以通过在新添加的元素上显式调用.formSelect()来解决此问题:

$("#addSelect").click(function(){
   $("#addSelect").addClass("disabled");
   $("#addSelect").hide();    
   $("#newContent").append("<div class='row'><div class='input-field col s12'><select> <option value='' disabled selected>Choose your option</option><option value='1'>Option 1</option><option value='2'>Option 2</option><option value='3'>Option 3</option> </select><label>Materialize Select</label><label>Materialize Select</label></div></div><button class='waves-effect waves-light bg-blue btn right' type='button'>Go</button>")

// Find the newly added element and call formSelect() on it.
.find("select").formSelect();
});

工作示例: https://codepen.io/sdflkjgnsdlfn/pen/pKZKOr

有一些CSS问题,但这应该可以帮助您!

答案 1 :(得分:0)

在第13行的materialize.min.css中,select设置为display: none;

Materialize.min.css select hidden