[英]Javascript breaks when I update html with Ajax
Having a problem with a webapp i've been working on lately, and it has to do with ajax reloading breaking javascript. 我最近一直在研究webapp的问题,这与ajax重新加载中断的javascript有关。
I have the following Ajax Call 我有以下Ajax电话
$.ajax({
type: "POST",
url: "/sortByIngredient/",
data: JSON.stringify(
{
selectedIngredients: tempDict
}),
contentType: "application/json; charset=utf-8",
success: function(data){
var curList = $("#drinkList").contents();
console.log(curList);
$("#drinkList").empty()
$("#drinkList").append(data)
and the following Html UL 及以下HTML UL
<div id = "drinkList" class="d-list">
<ul>
<li id='someID'>some Item</li>
<li id='someID2'>some Item2</li>
</ul>
</div>
I also have a jQuery callback set to activate on clicked list items. 我还有一个jQuery回调集,可在单击的列表项上激活。 On initial loading, all works well.
初次加载时,一切正常。 Once the ajax call occurs, and replaces the contents of #drinkList with another list, formatted identically.
一旦进行了ajax调用,并将#drinkList的内容替换为格式相同的另一个列表。 In case anyone is curious, here is the onClick callback:
如果有人好奇,这是onClick回调:
$("li").click(function()
{
window.currentDrink = $(this).attr("id");
console.log(window.currentDrink);
$.ajax({
url: "/getDrink/" + $(this).attr("id"),
type: "get",
success: function(data){
$("#ingDiv").html(data);
}
});
});
After I make that Ajax call, the list modifies correctly, but after that, no more javascript seems to work. 在我进行Ajax调用之后,列表会正确修改,但是之后,似乎没有更多的javascript工作了。 For example,the console.log is not called when i click on a list item, and the proper view doesnt update(#ingDiv, as shown in the above call)
例如,当我单击列表项时,未调用console.log,并且正确的视图没有更新(如上面的调用所示,#ingDiv)
Is my changing the HTML through Ajax breaking the javascript somehow? 我通过Ajax更改HTML是否以某种方式破坏了javascript? Am I missing something obvious?
我是否缺少明显的东西? If it isn't clear already, I am not a web developer.
如果还不清楚,我不是网络开发人员。
use event delegation like this - 这样使用事件委托-
$('#drinkList').on('click','li',function(){
// do your stuff here
});
As you are not a web developer - This is what your code should look after changes 由于您不是网络开发人员 -这是更改后代码的内容
$('#drinkList').on('click', 'li', function () {
window.currentDrink = $(this).attr("id");
console.log(window.currentDrink);
$.ajax({
url: "/getDrink/" + $(this).attr("id"),
type: "get",
success: function (data) {
$("#ingDiv").html(data);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.