jQuery插件消失

时间:2018-11-20 17:06:22

标签: jquery django jquery-plugins

我创建了一个非常简单的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不是函数

1 个答案:

答案 0 :(得分:0)

正如@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是没有标题或干扰主机页面的页面