首页 > 解决方案 > jQuery扩展功能失败

问题描述

我是 JQuery 的新手,正在绞尽脑汁试图理解为什么这个代码有效,但我的却没有。这是一个片段...

  window.onbeforeunload = function(event) {
    $('#mqTable tr.group1').css("background-color", "pink"); // This works
    $('#mqTable tr.group1').changeColor(); // Trying my own function fails


    // Prevent the warning message when leaving the page
    //        event.preventDefault();

    event.returnValue = "To be removed...";
  };

  jQuery.fn.extend({
    changeColor: function() {
      $(this).css("background-color", "pink");
      return $(this);
    }
  });

所以,我正在尝试创建自己的自定义函数,但我做错了。有任何想法吗?

标签: jqueryfunctionextending

解决方案


对不起,我不知道如何很好地使用 Stack Overflow,所以这是我能找到的唯一方法来格式化我的代码。

我可以通过单击按钮调用该函数,它理解它是一个扩展的 jQuery 函数。但是当我尝试从 onbeforeunload 函数中调用它时出现错误:TypeError: firstGroup1.children(...).changeColor is not a function

在此处输入图像描述

图片显示我单击了“更改颜色”按钮,并且 group1 行的颜色发生了变化……所以我知道我有一个有效的自定义 jQuery 函数。底部是我尝试从 onbeforeunload 函数调用相同函数时得到的错误。

以下是相关代码:

<script>
$( document ).ready(function($) {
    $('#changeColors').on('click',function(){
        try {
            var firstGroup1 = $('#mqTable tbody');
            firstGroup1.children("tr.group1").changeColor();
        }
        catch (err) {
            $('#errMsg').html(err);
        }
    });
});

window.onbeforeunload = function(event) {
    console.log("in onbeforeunload");
    var firstGroup1 = $('#mqTable tbody');
    try {
        firstGroup1.children("tr.group1, tr.group2").changeColor();
    } catch (err) {
        $('#errMsg').html(err);
    }

    // Prevent the warning message when leaving the page
    event.returnValue = "Oh boy";
};

jQuery.fn.extend({
    changeColor: function() {
        console.log("in changeColor");
        $(this).css("background-color", "pink");
        return $(this);
    }
});

推荐阅读