在ASP中AJAX加载了PartialView.. NET MVC -脚本运行不止一次

AJAX loaded PartialView in ASP.NET MVC - script runs more than once

本文关键字:MVC 脚本 运行 不止一次 NET PartialView ASP AJAX 加载      更新时间:2023-09-26

我有一些局部视图,它们都有一些类似的类()。更新,保存,取消),但它们的目的是不同的。在每个页面上,我都写了一个脚本来处理这些类,并使用ajax来加载PartialView。

一切都在工作,除了当我点击按钮重新加载页面,这个页面的脚本运行两次,再次点击,脚本运行3次。

$('#gridcontainer').load("/webdata/bank", {}, function () {
    alert('Load page'); // alert run 1 time when page load, it normal
    $('body').on('click', '.save', function () { // this function run n time when i load page n time.
          var c = confirm('Do you want save?')
          if (c) {
               $(this).val('Edit').removeClass('save').addClass('update');
               var v = $(this).closest('tr').find('td');
               v.eq(1).find('span').removeClass('hide');
               v.eq(1).find('input').attr('type', 'hidden');
               v.eq(2).find('input.cancel').attr('type', 'hidden');
               var id = $(this).data('id');
               // more code
          }
     });
}

你应该在重新加载时删除任何先前附加的事件,使用Jquery OFF

$('#gridcontainer').load("/webdata/bank", {}, function () {
    alert('Load page'); // alert run 1 time when page load, it normal
    $('body').off( "click", ".save").on('click', '.save', function () { // this function run n time when i load page n time.
          var c = confirm('Do you want save?')
          if (c) {
               $(this).val('Edit').removeClass('save').addClass('update');
               var v = $(this).closest('tr').find('td');
               v.eq(1).find('span').removeClass('hide');
               v.eq(1).find('input').attr('type', 'hidden');
               v.eq(2).find('input.cancel').attr('type', 'hidden');
               var id = $(this).data('id');
               // more code
          }
     });
}