[英]Jquery after Ajax request
I made an ajax request that replaces the html in my web page. 我提出了一个ajax请求,该请求替换了我网页中的html。 Now I have to "listen" into the button replaced with ajax (".button2").
现在,我必须“听”到用ajax(“ .button2”)替换的按钮。 I know that ajax works with asynchronous calls, so my source-page is not changed after the ajax call.
我知道ajax可用于异步调用,因此ajax调用后我的源页面不会更改。 This is my code.
这是我的代码。
$(document).ready(function(){
$(".button").on("click", function(){
var product = $(this).parent().parent();
var product_id = product.children(":first").text();
var quantity = product.find(".selectBoxCat :selected").text();
Cookies.set(product_id, quantity, {expires: 1});
$.ajax({
url: "/prog/php/updateCart.php",
dataType: "html",
cache: false,
success: function(data) {
$(".shopping-cart").replaceWith(data);
//update the cart
$(".badge").text(Object.keys(Cookies.get()).length);
}
});
});
$(".button2").on("click", function(){
alert("success"); //just a test
});
});
This code doesn't works for me. 此代码对我不起作用。 Button2 is the button added into the web-page after the ajax call.
Button2是ajax调用后添加到网页中的按钮。 How can I listen this button?
我怎么听这个按钮?
You declare the 您声明
$(".button2").on("click", function(){
alert("success"); //just a test
});
When this button doesn't exists, so the event is not blind. 如果此按钮不存在,则事件不是盲目的。 Try this:
尝试这个:
$(document).ready(function(){
$(".button").on("click", function(){
var product = $(this).parent().parent();
var product_id = product.children(":first").text();
var quantity = product.find(".selectBoxCat :selected").text();
Cookies.set(product_id, quantity, {expires: 1});
$.ajax({
url: "/prog/php/updateCart.php",
dataType: "html",
cache: false,
success: function(data) {
$(".shopping-cart").replaceWith(data);
//update the cart
$(".badge").text(Object.keys(Cookies.get()).length);
$(".button2").on("click", function(){
alert("success"); //just a test
});
}
});
});
});
It's a case of Event Delegation : your event listener doesn't work because there is no .button2
to attach it to at the moment you run that sentence. 这是事件委托的一种情况:您的事件监听器不起作用,因为在您运行该语句时没有将其附加到
.button2
事件。
$(document).on("click", ".button2", function(){
alert("success"); //just a test
});
This way the event registers at the document level, but triggers on .button2
. 这样,事件在文档级别注册,但在
.button2
上.button2
。 It would be more optimal anyway to use another element (maybe the surrounding div), instead of document, as the parent. 无论如何,使用另一个元素(可能是周围的div)代替document作为父元素将是最佳选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.