附加新元素后,函数不起作用

时间:2015-01-20 18:21:56

标签: javascript jquery html css ajax

我对jQuery函数创建的新元素的“click”操作有问题,但它不起作用。

我为这个链接创建了一个JSFiddle(JSFiddle),但它不能很好地工作,因为我无法在JSFiddle中调用Ajax请求。

我有这两个按钮,

<input type="button" onclick="invia('SIC-034031','', 's');" value="AGGIUNGI" style="height: 20px; width: 110px; background-color: #A5EFC5 ; color: #000000; font-family: Arial,Helvetica,sans-serif; font-size: 12px; background-repeat: no-repeat; background-position: left center;" id="iscriviSIC-034031" class="pulsanteIscrizioni" name="xaggiorna"/>&nbsp;
<input type="button" onclick="invia('SIC-034031','R', 's');" value="RISERVA" style="height: 20px; width: 110px; background-color: #F00000; color: #FFFFFF; font-family: Arial,Helvetica,sans-serif; font-size: 12px; background-repeat: no-repeat; background-position: left center;" id="iscriviRSIC-034031" class="pulsanteIscrizioni" name="xaggiorna"/>

第一次调用ajax函数时,按钮1会回答此输出:

OK;I;SIC-034031

按钮2仅用于擦除。按钮一创建。

<input id="iscriviSIC-034031" class="pulsanteIscrizioni" type="button" name="xaggiorna" style="height: 20px; width: 110px; background-color: #03F; color: #FFF; font-family: Arial,Helvetica,sans-serif; font-size: 12px;" value="TOGLI" onclick="invia('SIC-034031','');">

当我点击这个新按钮时,ajax函数会返回此信息,

OK;C;SIC-034031;;

按钮一个消失,按钮两个回来。 现在问题出在哪里,如果我点击第一个按钮,一切正常。如果我点击第二个按钮,它就不起作用。

请问你能帮我找到问题吗?

谢谢;)

1 个答案:

答案 0 :(得分:8)

jQuery在运行时只知道页面中的元素,因此添加到DOM的新元素无法被jQuery识别。为了解决这个问题,请使用event delegation,将新添加的项目中的事件冒泡到jQuery在页面加载时运行时的DOM中的某个点。许多人使用document作为捕捉起泡事件的地方,但没有必要在DOM树上走得那么高。理想情况下you should delegate to the nearest parent that exists at the time of page load.

$(".pulsanteIscrizioni").on("click", function()

是你现在拥有的。将其更改为 -

$(document).on("click", '.pulsanteIscrizioni',function()