我是JavaScript手段和编程的初学者,我遇到了个人项目的问题。我做了一个动漫大战网站从MySQL数据库获取一些信息,每个动漫都有十个视频和照片,通过一个随机按钮随机获取一个视频和照片的链接。问题是,如果我再次随机没有任何反应,它只能工作一次。我知道为了完成这项工作,我必须在第一次随机获得第二次随机后成功重写代码,但这将创建一个无限循环。有人可以帮我解决这个问题。
这是使用的代码:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
$('#random').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
})
}
});
})
});
</script>
答案 0 :(得分:0)
我理解 $。ajax 请求会覆盖初始 .imgResponsive 元素,对不对?除了覆盖 .imgResponsive 之外,您还会永久丢失附加到此元素的点击事件。
在这种情况下,您需要将事件附加到元素容器,例如
$(document).on('click', '.imgResponsive', function() {....
...
}
而不是
$('.imgResponsive').click(function(){ ....
答案 1 :(得分:0)
编写代码的方式,您只处理一个AJAX响应(除了第一个),无法处理通过单击#random按钮触发的更多AJAX请求。您需要编写处理按钮单击和AJAX响应的函数,而不是使用匿名函数;这样,它的模块化程度足以让您在将来可以收听和处理更多按钮点击。
这样的事情:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
$('#random').click(handleButtonClick);
});
function handleButtonClick(e){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
}
function handleResponse(response){
$('#hiddenPage').html(response);
}
});
</script>
编辑:可能发生的另一件事是,每次执行#random
时,您的$('#hiddenPage').html(response);
元素都会被覆盖。在这种情况下,每次处理AJAX响应时都需要将新的事件处理程序附加到新的#random
元素:
function handleResponse(response){
$('#hiddenPage').html(response);
$('#random').click(handleButtonClick);
}
答案 2 :(得分:0)
您必须注册EventListener才能继续。 试试这个:
<script>
var showImage = function(e){
e.preventDefault();
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
};
$(document).ready(function () {
$('document').on('click', '.imgResponsive', showImage);
$('document').on('click','#random', showImage);
});
</script>