javascript - 为什么是下面的||跳过有效值?

标签 javascript

以下代码根据第一个和子节点的存在设置this.statOffset:

console.log('Node: ', this.node.childNodes.item(0))
console.log('Node length: ', this.node.childNodes.item(0).length)

this.startOffset = this.node.length - 1 ||
    this.node.firstChild.length - 1 || 
    this.node.childNodes.item(0).length - 1 || 
    this.node.childNodes.item(0).firstChild.length - 1

一切正常。但在某些情况下,我在最后一个值中收到 Uncaught TypeError: Cannot read property 'length' of null: this.node.childNodes.item(0).firstChild.length - 1

奇怪的是,当 this.node.childNodes.item(0).length - 1 是有效值时,就会发生这种情况。 console.logs 输出:

Node: "a"
Node lenght: 1

为什么代码会跳过有效值并尝试执行最后一个值(无效值)?

编辑:节点结构:

<p>
    <strong>a</strong>
    b
    <span>
        <em>c</em>
    </span>
    d
    <strong>e</strong>
</p>

最佳答案

It works okay. But in some cases I get an Uncaught TypeError: Cannot read property 'length' of null in the last value: this.node.childNodes.item(0).firstChild.length - 1

两件事

  1. 您不需要将长度减 1,否则仅当长度大于 1 或 0 时才有效。
  2. Element 起,您需要使用 childNodeschildren 而不是长度没有长度属性

假设this指的是发生事件的元素,尝试

 this.startOffset = this.childNodes.length ||
   this.childNodes.item(0).childNodes.length;

或者使用hasChildNodes

 this.startOffset = this.hasChildNodes() ||
   this.childNodes.item(0).hasChildNodes();

关于javascript - 为什么是下面的||跳过有效值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36978889/

相关文章:

javascript - 覆盖基类的特权方法

javascript - 使用 JavaScript 将字节数组显示为图像

javascript - res.render() 之后的 Node JS : Error with res. download()

javascript - 如何覆盖 console.log

javascript - 对于相同的数据,如何根据网格排序对图表进行排序

javascript - 使用浏览器操作 Chrome 扩展程序

javascript - 使用 WebView 和 Javascript 推送通知

javascript - typescript 中的条件类型可以依赖于自身的值吗?

javascript - anchor 标记在 jquery slider 中不起作用

javascript - 尝试从输入中获取文件在 IE8 中返回对象错误