Jquery 插件消失

Jquery plugin disappears

我创建了一个我可以使用的非常简单的 jQuery .widget 插件:

<script type="text/javascript">
    (function( $ ) {
        $.fn.widget = function () {
            return this.each(function () {
                let $this = $(this);
                $this.load($this.attr("data-widget-source"), function (response, status, xhr) {
                    if (status == "error") {
                        const msg = "Sorry but there was an error: ";
                        $("#error").html(msg + xhr.status + " " + xhr.statusText);
                    }
                });
            });
        };
    }(jQuery)); 

    $(document).ready(function () {
        $('.widget').widget();
    });

但是当我尝试在使用 .load 加载的代码中使用它时,它似乎消失了:

$("#mymodal").load("/widget/29/", function(response, status, xhr) {
    if (status === "success"){                       
        M.FormSelect.init(document.querySelectorAll('select') , {});
        // Redirect submit event
        $("#slot_create_form").submit(function(e) {
           ajax_submit(e)
               .done(function( data, textStatus, jqXHR ) {
                   console.log("Slot from widget Form  data received: ");
                   console.log(data);
                   $('.widget').widget(); // Here fails 

           }).fail(function( jqXHR, textStatus, errorThrown ) {
                   console.log("Form ajax error received: ");
                   console.log(errorThrown);
           });
   });
}

它因错误而失败

TypeError: $(...).widget is not a function

正如@Taplar 所指出的,$("#mymodal").load() 注入的代码是一个完整的 THML 页面,它有自己对 JQuery 的引用。这是重新加载 JQuery,因此删除了插件。

使用 Django 中的条件扩展并提供没有脚本的页面的更简单版本更正了该问题:

{% extends request.no_frame|yesno:"frameless.html,frame.html,frame.html" %}

此请求属性由中间件设置:

class NoFrameMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if "frame" in request.GET:
            request.no_frame = {'frame': request.GET["frame"].lower() == 'false'}

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        return response

加载调用如下所示:

$("#mymodal").load("/widget/29/?frame=False")

frame.html 是常规页面,frameless.html 是没有 headers 或任何干扰主机页面的页面