简体   繁体   English

jQuery load()触发多次

[英]JQuery load() fires multiple times

This is my code: 这是我的代码:

$(document).ready(function () {
var na = $("#navDivA");
var nb = $("#navDivB");
var ca = $("#contentA");
var cb = $("#contentB");
var la = $("#home");
var lb = $("#about");
var firstSession = true;

na.on("click", function () {
    ca.load("home.html", function(){
         alert("Loaded");
       });
   });

nb.on("click", function () {
    cb.load("about.html");
   });
}); 

<div id="wrapper">
    <div id="navDivA"><a id="home">Home</a></div>
    <div id="navDivB"><a id="about">About</a></div>
    <div id="contentA"></div>
    <div id="contentB"></div>
 </div>

Why does it alert multiple times every time I start to click? 为什么每次我单击都会发出多次警报? How can I avoid this? 如何避免这种情况? I want to load the html file once. 我想一次加载html文件。

You can use function one instead of on . 您可以使用功能one代替on According to documentation 根据文件

The handler is executed at most once per element per event type. 每个事件类型的每个元素最多只能执行一次处理程序。

which seems to be what you need. 这似乎是您所需要的。 Change the code to 将代码更改为

na.one("click", function () {
    ca.load("home.html", function(){
         alert("Loaded");
    });
});

nb.one("click", function () {
    cb.load("about.html");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM