var question = 1;
function add_fields() {
question++;
var d = document.getElementById("add_question");
d.innerHTML += "<div id='remove_later'><div>Question Number " + question + " : </div><a id='remove' class='remove' style='color: #FFF; display: inline; float: right; margin-right: 25px; background: red; padding: 5px 10px;'>Delete Question</a><span><input type='text' class='dynamic_textfields' name='width[]' value='' /></span><br /><label class='answer_left' for='answer_1'>Answer Option 1 :</label><input class='dynamic_answer' type='text' name='answer_1' id='answer_1' /><br /><br /><label class='answer_left' for='answer_2'>Answer Option 2 :</label><input class='dynamic_answer' type='text' name='answer_2' id='answer_2' /><br /><br /><label class='answer_left' for='answer_3'>Answer Option 3 :</label><input class='dynamic_answer' type='text' name='answer_3' id='answer_3' /><br /><br /><label class='answer_left' for='answer_4'>Answer Option 4 :</label><input class='dynamic_answer' type='text' name='answer_4' id='answer_4' /><br /><br /><hr /></div>";
}
$('#remove').click( function (){
$('#remove_later').remove();
});
我使用javascript代码添加了一些动态输入字段。我想删除一些问题,因此我使用此jquery代码删除问题$('id').remove();
。但是,它不起作用。我不知道我犯了什么错误?我在jsbin上的完整代码...
答案 0 :(得分:1)
使用委托事件,因为在加载DOM后添加了html,请参阅delegated events:
$(document).on('click','#remove', function (){
$('#remove_later').remove();
});
答案 1 :(得分:1)
更新jsbin
function add_fields() {
question++;
var d = document.getElementById("add_question");
d.innerHTML += "<div id='remove_later'><div>Question Number " + question + " : </div><a id='remove' class='remove' style='color: #FFF; display: inline; float: right; margin-right: 25px; background: red; padding: 5px 10px;'>Delete Question</a><span><input type='text' class='dynamic_textfields' name='width[]' value='' /></span><br /><label class='answer_left' for='answer_1'>Answer Option 1 :</label><input class='dynamic_answer' type='text' name='answer_1' id='answer_1' /><br /><br /><label class='answer_left' for='answer_2'>Answer Option 2 :</label><input class='dynamic_answer' type='text' name='answer_2' id='answer_2' /><br /><br /><label class='answer_left' for='answer_3'>Answer Option 3 :</label><input class='dynamic_answer' type='text' name='answer_3' id='answer_3' /><br /><br /><label class='answer_left' for='answer_4'>Answer Option 4 :</label><input class='dynamic_answer' type='text' name='answer_4' id='answer_4' /><br /><br /><hr /></div>";
$('.remove').unbind('click');
$('.remove').click( function (){
$(this).closest('div').remove();
});
}
答案 2 :(得分:0)
由于元素是通过JavaScript添加到DOM的,因此您需要使用事件委派 -
$('body').on('click', '#remove', function (){