我对下面的HTML/jQuery脚本有问题。
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var count = 1;
$(function(){
$('#add').click(function(){
count++;
$('#container').append(count + '° posto: '+ '<input type="text" id="item_' + count + '" name="items[]" type="text" /><input type="submit" name="del" id="del" value="Elimina" /><br />');
return false;
});
$('#del').click(function(){
alert('prova');
return false;
});
});
</script>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<span>1° posto:</span><input type="text" id="item_1" name="items[]" maxlength=<?php echo $psw_length[1]; ?> />
<input type="submit" name="del" id="del" value="Elimina" /><br />
<div id="container"></div>
<input type="submit" name="add" id="add" value="Aggiungi" /><br />
<input type="submit" name="submit" value="Avanti >" />
</form>如果我单击第一个“消除”按钮,将出现警告,但如果我单击第二个、第三个、第四个按钮,则不会发生任何事情。
有没有人能帮帮我?谢谢!
发布于 2012-03-05 01:10:56
由于您的元素是动态添加的,因此需要使用on处理程序。
注意:您添加的是与del相同的id,这是错误的。对于每个元素,id应该是唯一的。
为了解决这个问题,您可以改用类:
class="del"然后将此代码与动态元素的on处理程序一起使用:
$('form').on('click', '.del', function(){
alert('prova');
return false;
});发布于 2012-03-05 01:11:53
有几件事:
id必须是唯一的!。从id选择器更改为name选择器
您需要使用委托事件,如on或delegate (live已弃用)。
$('#add').click(function(){
count++;
$('#container').append(count + '° posto: ' +
'<input type="text" id="item_' + count +
'" name="items[]" type="text" /> ' +
'<input type="submit" name="del" value="Elimina" /><br />');
// ===> Not duplicating the del id!!!
return false;
});
$('form').on('click', 'input[name="del"]', function(){ // <== delegate event.
alert('prova');
return false;
});发布于 2012-03-05 01:09:49
对于动态创建的控件,在事件上使用jquery 。不要使用live它已经过时了!
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var count = 1;
$(function(){
$('#add').on('click', function(){
count++;
$('#container').append(count + '° posto: '+ '<input type="text" id="item_' + count + '" name="items[]" type="text" /><input type="submit" name="del" id="del" value="Elimina" /><br />');
return false;
});
$('#del').on('click', function(){
alert('prova');
return false;
});
});
</script>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<span>1° posto:</span><input type="text" id="item_1" name="items[]" maxlength=<?php echo $psw_length[1]; ?> />
<input type="submit" name="del" id="del" value="Elimina" /><br />
<div id="container"></div>
<input type="submit" name="add" id="add" value="Aggiungi" /><br />
<input type="submit" name="submit" value="Avanti >" />
</form>**strong text**https://stackoverflow.com/questions/9556956
复制相似问题