所以我有这个代码。我想要完成一些事情 对于 javascript 人员来说可能很简单。如果选择某个选项 然后在 div 上添加一个输入字段。
<select name="amount" >
<option value="50">50$</option>
<option value="100">100$</option>
<option value="Other">Other</option>
</select>
<div id="custom_price">
</div>
所以我想在选择'其他'选项后添加输入字段。我知道有 解决此问题的简单方法,但我无法使其工作:
document.getElementById('custom_price').innerHTML += "<input type="text" name="amount"/>"
所以custom_div看起来像:
<div id="custom_price">
Custom price:<br>
<input type="text" name="amount"/>
</div>
最佳答案
最好的方法是实际制作 dom 元素。
var newInput = document.createElement("input");
newInput.type="text";
newInput.name="amount";
document.getElementById('custom_price').appendChild(newInput);
也许有这样的处理程序:
为您的选择分配一个 ID:<select name="amount" id="amount">
$("#amount").change( function() {
if( $(this).val() == "Other" ){
document.getElementById('custom_price').innerHTML = "";
var newInput = document.createElement("input");
newInput.type="text";
newInput.name="amount";
document.getElementById('custom_price').appendChild(newInput);
}
});
关于javascript/jquery 生成输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959186/