jQuery 函数不会全局读取属性
jQuery function won't read properties globally
我正在精简大量 jQuery 代码,我要做的第一件事是全局设置函数,以便它们可以在整个范围内使用和重用。一个功能是根据最高元素为元素设置相同的高度:
function setEqHeight(cont, classname) {
var maxHeight = 0;
$(cont).each(function(){
var prodName = $(classname,this);
$(prodName).each(function(){ if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } });
$(prodName).height(maxHeight);
});
}
我运行也是这样
setEqHeight('.containername','.classname');
这行得通,只要我在里面都调用 $j( document ).ready(function($) { });
但是我想全局设置函数,在文档外准备好,在里面调用函数。
当我在文档就绪范围外设置函数并在范围内调用它时,出现 Uncaught TypeError: Cannot read property 'each' of null
错误。就像它无法再读取 'containername' 一样。我很困惑,我做错了什么?
编辑:jsFiddle here。它在那里确实可以正常工作,这就引出了为什么它不能在生产环境中工作的问题
我在 中找到了罪魁祸首。我认为这与脚本运行的确切环境有关;洋红色。 Magento 与开箱即用的 jQuery 不兼容,所以我将函数中的美元符号更改为 jQuery,就像这样;
function setEqHeight(cont, classname) {
var maxHeight = 0;
jQuery(cont).each(function(){
var prodName = jQuery(classname,this);
jQuery(prodName).each(function(){ if (jQuery(this).height() > maxHeight) { maxHeight = jQuery(this).height(); } });
jQuery(prodName).height(maxHeight);
});
}
现在可以正常使用了。谢谢大家一起思考
我正在精简大量 jQuery 代码,我要做的第一件事是全局设置函数,以便它们可以在整个范围内使用和重用。一个功能是根据最高元素为元素设置相同的高度:
function setEqHeight(cont, classname) {
var maxHeight = 0;
$(cont).each(function(){
var prodName = $(classname,this);
$(prodName).each(function(){ if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } });
$(prodName).height(maxHeight);
});
}
我运行也是这样
setEqHeight('.containername','.classname');
这行得通,只要我在里面都调用 $j( document ).ready(function($) { });
但是我想全局设置函数,在文档外准备好,在里面调用函数。
当我在文档就绪范围外设置函数并在范围内调用它时,出现 Uncaught TypeError: Cannot read property 'each' of null
错误。就像它无法再读取 'containername' 一样。我很困惑,我做错了什么?
编辑:jsFiddle here。它在那里确实可以正常工作,这就引出了为什么它不能在生产环境中工作的问题
我在
function setEqHeight(cont, classname) {
var maxHeight = 0;
jQuery(cont).each(function(){
var prodName = jQuery(classname,this);
jQuery(prodName).each(function(){ if (jQuery(this).height() > maxHeight) { maxHeight = jQuery(this).height(); } });
jQuery(prodName).height(maxHeight);
});
}
现在可以正常使用了。谢谢大家一起思考