【问题标题】:Jquery plugin disappearsjQuery插件消失了
【发布时间】:2018-11-20 17:06:22
【问题描述】:

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

【问题讨论】:

  • 插件消失的主要方式是页面中不止一次包含 jQuery 库。
  • @Taplar 这正是正在发生的事情。您能否将您的评论作为回复,以便我选择它。
  • 我无法真正回答这个问题,因为它更像是一个评论。如果您想完整地描述问题并展示您是如何解决的,您可以回答您自己的问题。否则,如果问题被关闭/删除可能会更好,因为它本身并不能真正证明问题,而且我确信已经有其他现有问题在谈论这个问题。

标签: jquery django jquery-plugins


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2013-10-04
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多