【问题标题】:Getting extra ajax requests on(click)?获得额外的ajax请求(点击)?
【发布时间】:2013-12-30 02:27:28
【问题描述】:

如果您单击此网站上的顶部导航按钮,我正在处理http://techxpertschico.com/,您可能会在单击 5 次按钮后开始收到额外的 ajax 请求,您可以在检查器的网络部分看到这些请求。我无法弄清楚导致这些额外请求的原因,所以我不确定在我的代码中要更改什么。这个问题会导致极度滞后并最终关闭体验,直到你刷新所以......至少可以说这对我的用户体验不利。

这是一个典型的锚标签

<a class="ajaxAnchor" href="home.html">
    <div id="navOne" class="top">
        <span class="top">Home</span>
    </div>
</a>

这是锚点的 jQuery

$('.ajaxAnchor').on('click', function (event){ 
    event.preventDefault(); 
    var url = $(this).attr('href');
    $.get(url, function(data) {
        $('section.center').html(data);
    });
});

这是在这种情况下由主页按钮加载的示例 html

<script src="scripts/scripts.js"></script>
<h1>Welcome to TechXperts Chico!</h1>
<p>
    Welcome to the home of TechXperts! We are a computer, phone, and tablet repair shop located in Chico! We try to create a friendly and comfortable place for you to learn more about technology! Whether buying a new computer or trying to get the one you have to do what you want, everyone needs tech help at times. We offer a full range of repairs and tutorials to help you get the most out of your technology. If you have any questions feel free to call our office, or book an appointment below! Our goal is to help you to understand your device! We feel that is our responsibility to the community as the local computer experts. 
</p>
<a href="https://techxpertschico.youcanbook.me/" class="appointmentButton">Book Appointment Now</a>
<a href="mailto:techxpertschico@gmail.com" class="appointmentButton">Email TechXperts</a> 
<h1>Friendly staff always available to answer questions!</h1>

如果您还需要什么,请告诉我!

【问题讨论】:

  • 通过我对这些答案所做的更改,我的网站现在可以完美运行!谢谢大家!

标签: javascript jquery html css ajax


【解决方案1】:

在每个加载的资源上,您都会引用&lt;script src="scripts/scripts.js"&gt;&lt;/script&gt;,它会在每次加载新页面时向ajaxAnchor 元素添加新的点击处理程序。

改为使用事件委托并仅在主页中包含此脚本

【讨论】:

  • 当我不包含该脚本时,我的 javascript 由于某种原因停止工作?
  • 仅从 script.js 中删除 $('.ajaxAnchor').on('click', 点击处理程序并将其添加到不同的脚本文件中,并将该文件包含在主页中
  • 非常感谢。当您组合包含脚本但删除对其他类的不必要引用时,这是有意义的。非常感谢!在旁注......你喜欢这个设计吗?大声笑,它正在进行中,但我的第一个网站之一!
  • @CodeManiak 对我来说看起来有点暗
猜你喜欢
  • 2015-11-08
  • 1970-01-01
  • 2018-01-10
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多