>仅供参考,我已经阅读了相关线程未捕获的类型错误:无法读取未定义的属性"到小写"并尝试实现该想法。不过,我还是得到了经典
未错误,我不知道捕获的类型错误:无法读取未定义的属性"toSmallCase">
它来自我的代码中的哪一行,因为错误点在 jQuery 中。我的代码是
ReadinessColorSetter = (function () {
this.ColorToRange = {
'#f65314': [0, 30],
'#ffbb00': [31, 70],
'#7cbb00': [70, 100]
}
this.SetReadiness = function (ipt) {
// ipt: input element containing
var val = $(this).val(),
newcolor = "#FFF"; // default
for (var hexcode in this.ColorToRange) {
var range = this.ColorToRange[hexcode];
if (val >= range[0] && val < range[1]) {
newcolor = hexcode;
break;
}
}
$(ipt).parent().children().last().css('background-color', newcolor);
}
return this;
})();
// On page load, set the color of the readiness
$(function () {
$('input[class="completeness"]').each(function (el) {
ReadinessColorSetter.SetReadiness(this);
});
});
// When the readiness value is changed, set the color of the readiness
//$('input[class="completeness"]').change(function () {
//ReadinessColorSetter.SetReadiness(this);
//});
$(document).on('change', $('input[class="completeness"]'), function (el) {
ReadinessColorSetter.SetReadiness($(el.target));
});
$('#change-submitted').click(function () {
alert('Change submitter clicked'); // TEST
});
如您所见,我已经注释掉了我认为的问题并尝试实施正确的修复程序。
关于这个问题有什么指导吗?
似乎是无效的:
$(document).on('change', $('input[class="completeness"]'), function (el) {
//-----------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----it should be a string
如您所见,您已经传递了一个jquery对象,而在描述中,您应该看到它需要一个CSS选择器的字符串,例如:
$(document).on('change', 'input.completeness', function (el) {
在方法中:
var val = $(ipt).val(),
并且 if 条件应为:
if (val >= range[0] && val <= range[1]) {
newcolor = hexcode;//--^^----------------should be less than equal instead
break;
}
查看 :
// On page load, set the color of the readiness
$(function () {
$('input[class="completeness"]').each(function (el) {
ReadinessColorSetter.SetReadiness(this);
});
});
$.each(( 闭包具有 [index,elements] 的参数,您将解包的元素发送到 SetReadiness 函数,您应该执行以下操作:
(function () {
$('input[class="completeness"]').each(function (index, elem) {
ReadinessColorSetter.SetReadiness(elem);
});
})();
代码中还有另一个错误,即多次将元素包装在jQuery元素对象中,这会导致两种不同类型的对象被发送到SetReady函数,该函数在一种情况下是标准元素对象,在另一种情况下是jQuery元素对象。
将函数输入规范化为标准元素对象或 jQuery 元素对象,这样做可以消除混乱的代码,即。
this.SetReadiness = function (ipt) {
// ipt: element pre wrapped inside of a jQuery object.
var val = ipt.val(),
newcolor = "#FFF"; // default
for (var hexcode in this.ColorToRange) {
var range = this.ColorToRange[hexcode];
if (val >= range[0] && val < range[1]) {
newcolor = hexcode;
break;
}
}
ipt.parent().children().last().css('background-color', newcolor);
}
留给你一个将纯jQuery元素对象作为参数的函数,或者你可以发送一个标准元素对象,然后将其包装在SetReady函数中的jQuery元素对象中。
希望这可以解决您遇到的一些问题,每当您收到未定义的错误时,请始终检查您是否将有效对象包装在 $(对象( 中。
像这样标准化所有内容将清除您的错误,并为您提供干净且可读的代码。我没有看过你的代码的功能,只专注于清除你未定义的错误。