此脚本已动态添加.它具有超时功能,意味着它每5秒运行一次.
dynamicjs.php
$(document).ready(function(){
(function( $ ){
$.fn.baslatmesajlari = function() {
setInterval(function(){
console.log("I am running");
}, 5000);
return this;
};
})( jQuery );
});
$("body").baslatmesajlari();
Run Code Online (Sandbox Code Playgroud)
我将此函数加载到div使用;
$("#temporarycontent").load("dynamicjs.php");
Run Code Online (Sandbox Code Playgroud)
而当我这样做
$("#temporarycontent").empty();
Run Code Online (Sandbox Code Playgroud)
该脚本仍在运行.我怎么能阻止它运行?
你不能,你需要一个函数intervalId返回的句柄setInterval或在插件上提供一个API,以便销毁它并自行清理.最简单的方法是将插件的状态附加到应用它的DOM元素.
(function ($) {
const PLUGIN_NAME = 'baslatmesajlari';
function Plugin($el) {
this.$el = $el;
this._timerId = setInterval(function () {
console.log('running');
}, 2000);
}
Plugin.prototype.destroy = function () {
this.$el.removeData(PLUGIN_NAME);
clearInterval(this._timerId);
};
$.fn[PLUGIN_NAME] = function () {
if (!this.data(PLUGIN_NAME)) this.data(PLUGIN_NAME, new Plugin(this));
return this;
};
})(jQuery);
$(function () {
var plugin = $('#plugin').baslatmesajlari().data('baslatmesajlari');
$('#destroy').click(function () {
plugin.destroy();
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="plugin"></div>
<button id="destroy">Destroy plugin</button>Run Code Online (Sandbox Code Playgroud)