删除按钮不起作用,她是原始版本:jsfiddle,我也试图添加按钮添加/删除问题,我可以复制相同的代码(到:添加/删除问题)?添加新输入工作正常
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#optionid');
var i = $('#optionid').size() + 1;
$('#addoption').on('click', function() {
$('<p><div class="row">'+
'<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">'+
'<label for="">Option #' + i +':</label>'+
'<input type="text" class="form-control" id="" name="option[' + i +'][option]" >'+
'</div>'+
'<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">'+
'<label for="">Value #' + i +':</label>'+
'<input type="number" class="form-control" id="" name="value[' + i +'][value]" >'+
'</div>'+
'<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">'+
'<div class="imad">'+
'<button type="button" class="btn btn-danger" id="removeoption" >Remove button</button>'+
'</div>'+
'</div>'+
'</div> </p>').appendTo(addDiv);
i++;
return false;
});
$(document).on("click", "#removeoption", function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<div id="optionid">
<div class="row">
<p>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<label for="">Option #1:</label>
<input type="text" class="form-control" id="" name="option[1][option]" >
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
<label for="">Value #1:</label>
<input type="number" class="form-control" id="" name="value[1][value]" >
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
<div class="imad">
<button type="button" class="btn btn-success" id='addoption'>Add Question</button>
</div>
</div>
</p>
</div>
</div>
答案 0 :(得分:1)
创建动态元素时需要
Event delegation
。使用classes
,因为不能有多个元素具有相同的id
使用event.preventDault()
作为anchor
标记的默认行为是导航/重定向,我们希望有点击处理程序而不是。
试试这个:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').click(function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#p_scents').on('click', '.remScnt', function(e) {
e.preventDefault();
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
&#13;
* {
font-family: Arial;
}
h2 {
padding: 0 0 5px 5px;
}
h2 a {
color: #224f99;
}
a {
color: #999;
text-decoration: none;
}
a:hover {
color: #802727;
}
p {
padding: 0 0 5px 0;
}
input {
padding: 5px;
border: 1px solid #999;
border-radius: 4px;
-moz-border-radius: 4px;
-web-kit-border-radius: 4px;
-khtml-border-radius: 4px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
</label>
</p>
</div>
&#13;