我在动态生成表单时遇到问题。 这是我的代码:
<script>
$(document).ready(function(){
$('#add').on('click',function(){
$('<p><input type="text" id="testo"/><input type="button" name="remove" id="remove" Value="rimuovi" /></p>').appendTo(content);
});
//$('#remove').on('click', function() {
//$(this).parents('p').remove();
//});
$( 'body' ).on( "click", "#remove", function() {
console.log( $( this ).text() );
});
});
</script>
</head>
<body>
<div id="content">
<p>
<input type="text" value="" placeholder="Input Value"/>
<input type ="checkbox" ></input>
<input type="button" name="remove" id="remove" Value="rimuovi"></input>
<input type="button" name="add" id="add" Value="add"></input>
</p>
</div>
</body>
添加字段工作正常,甚至是静态写入的删除按钮。问题在于按钮&#34;删除&#34;由jquery生成。它不起作用,并且不会在控制台上生成任何输出。谢谢!
答案 0 :(得分:0)
试试这个:您多次使用相同的id
。要么使用唯一的id
,要么使其成为类。见下面的代码
$(document).ready(function(){
$('#add').on('click',function(){
$('<p><input type="text" id="testo"/><input type="button" name="remove" class="remove" Value="rimuovi" /></p>').appendTo(content);
});
//$('#remove').on('click', function() {
//$(this).parents('p').remove();
//});
$( 'body' ).on( "click", "input[type='button'].remove", function() {
console.log( $( this ).text() );
});
});
答案 1 :(得分:0)
$(document).ready(function() {
$('#add').on('click', function() {
$('<p><input type="text" id="testo"/><input type="button" name="remove" id="remove" Value="rimuovi" /></p>').appendTo(content);
});
$(document).on('click', '#remove', function() {
$(this).parents('p').remove();
});
$('body').on("click", "#remove", function() {
console.log($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<p>
<input type="text" value="" placeholder="Input Value" />
<input type="checkbox"></input>
<input type="button" name="remove" id="remove" Value="rimuovi"></input>
<input type="button" name="add" id="add" Value="add"></input>
</p>
</div>
这是代码
您需要在文档上运行单击动态加载元素