![](/img/trans.png)
[英]load an external js file before script in body executes (without jQuery)
[英]jQuery load script executes many times
我有一個簡單的方法來加載內容,並將其替換為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的鏈接時,按預期在控制台上看到“正在運行...”。 我第二次這樣做時,“正在運行...”在控制台上打印了兩次。 第三次,該消息在控制台上出現4次,依此類推。 我不知道問題出在哪里。 當我為每個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);
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.