【问题标题】:Reference to nextElementSibling undefined引用 nextElementSibling 未定义
【发布时间】:2016-06-21 03:44:56
【问题描述】:

我正在构建一个产品滑块,每次滑动后都会更新其状态。要查找对幻灯片中上一个和下一个元素的引用,我使用了 nextElementSibling/previousElementSibling。这在桌面版 Chrome 中运行良好,即使幻灯片是使用 Ajax 动态加载的。

但是,在移动版 Safari 和 Chrome 上,我收到以下错误:

TypeError: null is not an object (evaluating 'currentProduct.dataset') 

似乎一旦我到达幻灯片中使用 ajax 加载的元素,就不再有 nextElementSibling/previousElementSibling 引用了。

updateState: function (direction, xOffset, outerOffset) {

        // Old current product
        var currentProduct = this.state.currentProduct;

        // Set new current product
        if (direction === 'next') {
            currentProduct = this.state.currentProduct.nextElementSibling;
        } else if (direction === 'prev') {
            currentProduct = this.state.currentProduct.previousElementSibling;
        }

        // Set new state
        this.state.currentProduct = currentProduct;
        this.state.prevProductUrl = currentProduct.dataset.prev;
        this.state.nextProductUrl = currentProduct.dataset.next;

        // Load new sibling
        if (currentProduct.nextElementSibling === null) {

            $.get(this.state.nextProductUrl).done( function(data) {
                // Insert next product
                this.insertProduct(data, 'next');

                this.setContainerSize(this.productContainer.children.length);
            }.bind(this));

        } else if (currentProduct.previousElementSibling === null) {

            $.get(this.state.prevProductUrl).done( function(data) {
                // Insert next product
                this.insertProduct(data, 'prev');

                this.setContainerSize(this.productContainer.children.length, true);
            }.bind(this));
        }

        // Set new xOffset
        this.state.xOffset = xOffset;

        // Update offset of container element
        this.state.outerOffset = outerOffset;
    }

使用 jQuery 的 .next()/.prev() 函数也无济于事,但结果相同。

任何帮助将不胜感激!

【问题讨论】:

  • 通过该错误消息,我将检查您分配给 currentProduct 的值。我怀疑是null。只需在设置其值后添加console.log (currentProduct); 并在调试控制台上检查即可。
  • 谢谢,确实是null,那是因为元素加载ajax时this.state.currentProduct.nextElementSibling的值是null。奇怪的是,这只发生在移动 Chrome 和 Safari 中。桌面 Chrome 不返回 null,而是返回实际的下一个/上一个元素。

标签: javascript jquery ajax dom dom-manipulation


【解决方案1】:

想通了.. 由于使用代理,ajax 请求无法正常工作.. 糟糕。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-29
    • 2011-07-14
    • 2012-01-14
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多