我有一个动态容器,当你通过从“data-target”属性加载文件名来点击链接时会更新。我不希望同一个链接被点击两次(有效加载同一页面两次)。
有没有办法阻止这种情况?
JQuery的:
$(document).ready(function(){
// Set trigger and container variables
var trigger = $('#nav ul li a'),
container = $('#ajaxContainer');
// Fire on click
trigger.on('click', function(){
// Set $this for re-use. Set target from data attribute
var $this = $(this),
target = $this.data('target');
// Load target page into container
container.load(target);
console.log(target);
// Stop normal link behavior
return false;
});
});
HTML:
<DOCTYPE html>
<html>
<head>
<title>My Site</title>
<link rel="stylesheet" type="text/css" href="/css/main.css" />
</head>
<body>
<nav id="nav">
<ul>
<li><a href="#" data-target="/home.php">Home</a></li>
<li><a href="#" data-target="/modules/Movies/index.php">Movies</a></li>
</ul>
</nav>
<div id="ajaxContainer">
<img id="logo" src="/images/logo.png" />
<?php include('home.php'); ?>
</div>
<script src="/js/jquery-1.12.4.min.js"></script>
<script src="/js/app.js"></script>
</body>
</html>
答案 0 :(得分:1)
您可以删除data-target
并在load()
完成后重新设置它(在回调参数上):
// Fire on click
trigger.on('click', function(){
// Set $this for re-use. Set target from data attribute
var $this = $(this),
target = $this.data('target');
$this.removeAttr('data-target'); // delete de target
// Load target page into container only if it's target set
if(target) {
container.load(target);
}
console.log(target);
// Stop normal link behavior
return false;
});