我有一个简单的方法来加载内容并将其替换为 div 元素:
$("a[data-ajax='true']").on('click', function (event) {
event.preventDefault();
var goToLink = this.href;
animateLink(this);
$('#ajax-target').fadeTo(0.2, 0.5, function () {
lastLink = currentLink;
currentLink = goToLink;
$('#ajax-target').load(goToLink, {}, function () {
$('body').scrollTop(0);
$('#ajax-target').fadeTo('slow', 1);
});
});
});
现在我加载每个ajax HTML 代码,其中包含以下代码:
<script>
console.log('Running...')
</script>
第一次单击加载 ajax 的链接时,我按预期在控制台上看到“正在运行...”。第二次这样做时,“正在运行...”在控制台上打印两次。第三次这个消息我在控制台上收到了四次,依此类推。我不知道问题出在哪里。当我加载每个 ajax 请求的 HTML 代码并按照 html() 方法替换它时,同样的问题。有人知道出了什么问题吗?
编辑 在这里回答之后,我现在有了以下有效的代码:
<script>
var currentLink, lastLink;
function animateLink(obj) {
var el = $(obj);
var animate = el.attr('data-animation');
if (animate != undefined) {
animate = animate.toLowerCase();
animate = animate == 'false' ? false : true;
} else {
animate = true;
}
if (animate) {
el.toggle('explode');
}
}
$(document).ready(function () {
$("a[data-ajax='true']").on('click', function (event) {
event.stopImmediatePropagation();
event.preventDefault();
var goToLink = this.href;
animateLink(this);
$('#ajax-target').fadeTo(0.2, 0.5, function () {
lastLink = currentLink;
currentLink = goToLink;
$('#ajax-target').load(goToLink, {}, function () {
$('body').scrollTop(0);
$('#ajax-target').fadeTo('slow', 1);
});
});
});
});
function historyBack() {
$('#ajax-target').fadeTo(0.2, 0.5, function () {
var newLink = lastLink;
lastLink = this.href;
currentLink = newLink;
$.get(newLink, {}, function (response) {
$('body').scrollTop(0);
$('#ajax-target')
.html(response)
.fadeTo('slow', 1);
});
});
}
</script>
这直接位于网站上。当ajax请求完成时,这部分不会被删除。始终更改的部分如下:
<div class="content-wrapper" id="ajax-target">
@Html.Partial("LayoutContentHeader")
<section class="content">
@RenderBody()
</section>
</div>
加载的页面是一个MVC页面,其中主框架不包含任何HTML或BODY标签,只有需要替换的内容,此外有时还包含脚本(我上面的脚本如何):
@if (IsAjax)
{
if (isMainLayout)
{
@Html.Partial("LayoutContentHeader")
<section class="content">
@RenderBody()
</section>
}
else
{
@RenderBody()
}
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
}
正如你所看到的,当我们进行ajax请求时,我只发送重要的内容。
按下链接的代码例如:
<a href="/wilhelmshaven/hse/" data-ajax="true" class="btn btn-block btn-social" style="color: white !important; background-color: rgb(243,156,18)">
<i class="fa fa-th"></i>HSE
</a>
周围没有链接(这会强制冒泡)。
最佳答案
尝试添加此代码
$("a[data-ajax='true']").on('click', function (event) {
event.stopImmediatePropagation();
var goToLink = this.href;
animateLink(this);
$('#ajax-target').fadeTo(0.2, 0.5, function () {
lastLink = currentLink;
currentLink = goToLink;
$('#ajax-target').load(goToLink, {}, function () {
$('body').scrollTop(0);
$('#ajax-target').fadeTo('slow', 1);
});
});
});
关于javascript - jQuery 加载脚本执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29937249/