You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

触发Uncaught TypeError读取getAttribute报错 价格排序功能失效

报错原因

你的代码存在两处核心语法错误导致触发该报错:

  • 内层循环条件写错:两个排序函数的内层for循环判断条件写的是i < big_content.children.length,应该判断j的范围,否则j会无限自增超出子元素的索引范围,取到undefined后调用getAttribute就会抛出错误
  • 元素取值语法错误:大小判断的代码中错误写为big_content.children.length[j],children.length是数值类型,不存在下标属性,应该改为big_content.children[j]

另外补充优化建议:直接操作实时的DOM子元素集合排序时,DOM替换会导致集合的索引实时变动,容易触发排序逻辑异常,建议先把子元素转为静态数组后排序,再统一更新DOM,稳定性和性能更好。

修复后的完整代码
const big_content = document.querySelector('#big_content');
document.querySelector('#sort_low').onclick = function() {
    low__high('data-price')
}
document.querySelector('#sort_high').onclick = function() {
    high__low('data-price')
};

function low__high(sortType) {
    const big_content = document.querySelector('#big_content');
    // 先转成静态数组避免DOM变动影响索引
    const items = Array.from(big_content.children);
    items.sort((a, b) => {
        return +a.getAttribute(sortType) - +b.getAttribute(sortType)
    })
    // 统一更新DOM
    items.forEach(item => big_content.appendChild(item))
    console.log('Sort by price: low to high');
}

function high__low(sortType) {
    const big_content = document.querySelector('#big_content');
    const items = Array.from(big_content.children);
    items.sort((a, b) => {
        return +b.getAttribute(sortType) - +a.getAttribute(sortType)
    })
    items.forEach(item => big_content.appendChild(item))
    console.log('Sort by price: high to low');
}

function insertAfter(elem, refElem) {
    return refElem.parentNode.insertBefore(elem, refElem.nextSibling)
}

内容的提问来源于stack exchange,提问作者Umarjon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:36:04