以下代码根据第一个和子节点的存在设置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 或 0 时才有效。
- 自 Element 起,您需要使用
childNodes
或children
而不是长度没有长度属性
假设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/