【问题标题】:JQuery extending a function is failingjQuery扩展功能失败
【发布时间】:2020-08-21 20:18:05
【问题描述】:

我是 JQuery 的新手,正在绞尽脑汁试图理解为什么这个代码有效,但我的却不行。这是一个sn-p...

  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);
    }
  });

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

【问题讨论】:

  • 我想要一个可以设置 sessionStorage 的函数,这只是对我能否从 JQuery 对象调用函数的测试。
  • 在这里工作正常
  • 哈!哦不!我绞尽脑汁想弄明白可能出了什么问题。我认为返回 $(this) 对于链接是必要的。还是它已经“在幕后”这样做了?我真的在拉稻草!
  • 您的代码似乎可以正常工作。如果不适合您,请发minimal reproducible example 说明问题
  • 我可以通过在 try/catch 块中找到错误消息 TypeError: $(...).changeColor is not a function 不过仍然不知道为什么!

标签: jquery function extending


【解决方案1】:

对不起,我不知道如何很好地使用 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);
    }
});

【讨论】:

  • 好吧...我想通了.... window.onbeforeunload = function(event) { 现在在 document.ready 中定义,它似乎工作正常。
猜你喜欢
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2013-01-07
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多