gpt4 book ai didi

jQuery 单击操作仅在每次页面刷新时触发一次

转载 作者:行者123 更新时间:2023-12-03 22:44:09 25 4
gpt4 key购买 nike

我在网站的管理部分编写了一段 jQuery 代码,可以在不刷新页面的情况下使网站离线。它工作得很好,但有一件事:

When I click on TURN ON the ajax call is made accurately and all the classes are changed and the text is changed the TURN OFF. However, when I click on this text, nothing happens. If I reload the page, then I will be able to.

$("#switch_off").click(function() {
$("#switch_off").html("<img style=\"padding-left:15px;\" src=\"/img/admin/ajax-loader.gif\">");
$('#switch_off').removeClass('ttip_b')
$.ajax({
url: "/settings/SwitchOffline",
type: "get",
data: '',
success: function(responseText, statusText, xhr, $form){ // Trigger when request was successful
$("#site_status").html("<span id=\"offline\" class=\"lbl error_bg\">Offline</span><span id=\"switch_on\" class=\"ttip_b\" title=\"Click to place Site Online\">Turn On</span>");
},
error: function(responseText){
//alert(responseText);
}
});
return false;
});

$("#switch_on").click(function() {
$("#switch_on").html("<img style=\"padding-left:15px;\" src=\"/img/admin/ajax-loader.gif\">");
$('#switch_on').removeClass('ttip_b')
$.ajax({
url: "/settings/SwitchOnline",
type: "get",
data: '',
success: function(responseText, statusText, xhr, $form){
$("#site_status").html("<span id=\"online\" class=\"lbl ok_bg\">Online</span><span id=\"switch_off\" class=\"ttip_b\" title=\"Click to place Site Offline\">Turn Off</span>");
},
error: function(responseText){
//alert(responseText);
}
});

return false;
});

ONLINE OFFLINE

带有一些 PHP 的 HTML 代码

<div class="user_info user_sep" style="width:90px;">
<p class="sepH_a">
<strong>Site Status</strong>
</p>
<?php
//debug($site_offline);
if($site_offline){
?>
<span id="site_status">
<span id="offline" class="lbl error_bg">Offline</span>
<span id="switch_on" class="ttip_b" title="Click to place Site Online">Turn On</span>

</span>
<?php }else{ ?>
<span id="site_status">
<span id="online" class="lbl ok_bg">Online</span>
<span id="switch_off" class="ttip_b" title="Click to place Site Offline">Turn Off</span>

</span>
<?php } ?>
</div>

最佳答案

请尝试使用事件委托(delegate),因为每次点击都会重写 HTML,并且绑定(bind)会丢失。通过使用事件委托(delegate),您可以为 DOM 中的当前元素以及将来将附加到 DOM 的元素(例如 AJAX 调用产生的元素)绑定(bind)事件。

使用

$("#site_status").on("click", "#switch_off", function() {
...
});

$("#site_status").on("click", "#switch_on", function() {
...
});

而不是

$("#switch_off").click(function() {
...
});

$("#switch_on").click(function() {
...
});

如果#site_status也被覆盖,则使用文档

关于jQuery 单击操作仅在每次页面刷新时触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14186505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com