![](/img/trans.png)
[英]Why does this JS function not work more than once if I use it multiple times on 1 page?
[英]AJAX changing content of page does not work more than once?
我正在嘗試加載不同的視圖而不使用JQUERY> AJAX重新加載。 第一次運行正常,但第二次觸發呼叫並加載頁面。
這是我正在使用的按鈕:第一次:
<p><a href="{{ URL::route('onboarding-ajax', ['i' => '2']) }}" id="next-step" next-step-id="2">Start <i class="icon arrow-right"></i></a></p>
第二次:
<p><a href="{{ URL::route('onboarding-ajax', ['i' => '3']) }}" id="next-step" next-step-id="3" >Next</a></p>
這是腳本:
<script>
$('#next-step').on('click', function (e) {
e.preventDefault();
var that = $(this),
url = that.attr('href'),
type = 'GET',
step_id = that.attr('next-step-id'),
width = (step_id / 32)*100 + '%';
$.ajax({
url: url,
type: type,
success: function(response) {
$('#content-wrap').html(response.view);
window.history.pushState({path:url},'',url);
return false;
}
});
});
</script>
知道做錯了什么嗎?
如果您的#next-step
元素位於#content-wrap
內部,則當您替換#content-wrap
內容時,該元素將消失。 如果新內容中還包含#next-step
,則它是具有相同ID的另一個元素,並且不會像以前的內容那樣附加click
處理程序。
挽救它的最簡單方法是使用“實時”處理程序-不是在#next-step
,而是在父級上。 嘗試這個:
$('#content-wrap').on('click', '#next-step', function (e) {
這告訴#content-wrap
注意#next-step
上的click
事件。 由於您不替換#content-wrap
本身,因此該處理程序將繼續存在,並且即使替換#next-step
也會捕獲事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.