jquery - 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);
}
});
所以,我正在尝试创建自己的自定义函数,但我做错了。有任何想法吗?
解决方案
对不起,我不知道如何很好地使用 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);
}
});
推荐阅读
- css - 如果设置了颜色,如何启用悬停颜色更改?
- algorithm - 算法分析,什么算作关键比较?
- next.js - next-i18next 在使用 getstaticprops 加载页面后重新渲染 _app.js
- python - 具有不同名称的字典以及如何打印名称
- python - Tweepy 4.0:“'Listener'对象没有属性'running'”错误?
- python - 直方图 - 当有 2 个以上的同一个单词的字母时下一行
- python - 在 python 中保存和加载函数
- flutter - Flutter 视频播放器,例如 Youtube、Amazon Prime
- python - 如何在条形图上显示平均值
- mysql - Mysql FIND_IN_SET GET ALL 列