javascript - 为什么我的 firstNode.nodeValue 返回 null?
问题描述
我正在尝试将第一个 p 标签拆分为 3 个单独的行并使用 javascript 节点将它们显示在第二个 p 标签中。但我得到一个空的返回值。
Chrome 向我抛出一个运行时错误,说它“无法读取属性 'nodeValue' of null”
有人可以帮助我吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style media="screen">
.hideOriginal {
display: none;
}
</style>
</head>
<body>
<p id="oneLine">
<span>Hi my name is John Doe</span>
<span>I'm learning web development</span>
<span>I'm 100 years old.</span>
</p>
<p class="lineBreak"></p>
<input type="button" name="" id="fixLineBreak" value="Line Break">
</body>
<script type="text/javascript">
const breakLineFunction = () => {
const spans = document.querySelector("#oneLine");
document.querySelector("#oneLine").setAttribute("class", "hideOriginal")
let newLine = "";
const first = spans.firstChild.firstChild.nodeValue;
const second = spans.firstChild.nextElementSibling.firstChild.nodeValue;
const last = spans.lastChild.firstChild.nodeValue;
const brk = "<br><br>";
newLine = `${first}${brk}${second}${brk}${last}`;
document.querySelector(".lineBreak").innerHTML = newLine;
}
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#fixLineBreak").addEventListener("click", breakLineFunction);
})
</script>
</html>
解决方案
const breakLineFunction = () => {
const spans = document.querySelector("#oneLine");
document.querySelector("#oneLine").setAttribute("class", "hideOriginal")
let newLine = "";
const first = spans.firstChild.nodeValue;
const second = spans.firstChild.nextElementSibling.firstChild.nodeValue;
const last = spans.lastElementChild.textContent
;
const brk = "<br><br>";
newLine = `${first}${brk}${second}${brk}${last}`;
document.querySelector(".lineBreak").innerHTML = newLine;
}
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#fixLineBreak").addEventListener("click", breakLineFunction);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style media="screen">
.hideOriginal {
display: none;
}
</style>
</head>
<body>
<p id="oneLine">
<span>Hi my name is John Doe</span>
<span>I'm learning web development</span>
<span>I'm 100 years old.</span>
</p>
<p class="lineBreak"></p>
<input type="button" name="" id="fixLineBreak" value="Line Break">
</body>
</html>
推荐阅读
- project - 无法在 Eclipse 2018-12 和 JBPM7.15 中作为 JBPM 项目运行
- python - 回归的概率 SVM
- python-3.x - Python - Google Sheets API - 未写入指定范围
- javascript - d3 v5 在地图上定位图钉图像
- node.js - node-fetch:为什么推荐使用“signal”而不是“timeout”?
- java - 改进列表列表?
- x86 - PREFETCHT2 读取到什么级别的缓存?
- sml - 如何将一个列表插入另一个列表而不连接它们
- matlab - 如何设置 csvread 的结束限制?
- javascript - 谷歌图表 vAxis 值在第一次点击时不可见