javascript - 当我访问子元素时,函数在循环后不继续
问题描述
这是我面临问题的代码:
内部:
<div id="test">
<p>Hello World! <b> Some Bold <i> RED(and also Italic)</i>
</b>
<i>text</i>
</p>
<button onclick="myFunction(this)">Try it</button>
<p id="demo"></p>
</div>
内部脚本
function myFunction(find) {
var c = find.parentNode.children;
var i;
for (i = 0; i <= c.length; i++)
{
c[i].children[0].children[0].style.color="red";
}
alert("Something in the alert");
}
我的问题是,为什么不
alert("警报中有内容");
正在执行?
解决方案
问题出在c[i].children[0] is undefined中。这里 javascript 停止执行。
所以使用 try catch 方法来处理这种情况。
<!DOCTYPE html>
<html>
<body>
<div id="test">
<p>Hello World! <b> Some Bold <i> RED(and also Italic)</i>
</b>
<i>text</i>
</p>
<button onclick="myFunction(this)">Try it</button>
<p id="demo"></p>
</div>
<script>
function myFunction(find) {
var c = find.parentNode.children;
var i;
for (i = 0; i <= c.length; i++)
{
try {
c[i].children[0].children[0].style.color="red";
}
catch(err) {
}
}
alert("Something in the alert");
}
</script>
</body>
</html>
推荐阅读
- rest - 如何处理微服务架构中的指数调用层次结构?
- image - Fluttes 不更新图像状态
- c++ - 在 Docker 中调试 .NET Core 应用程序 - 附加到非托管代码
- google-apps-script - 谷歌表 onedit 方法会导致脚本崩溃,否则会起作用?
- python - 使用pandas python按组计算字符串中的单词数
- reactjs - Hooks 和 Redux / useEffect 聊天机器人
- django - Django 自定义模型管理器
- html - 如何为 django-google-analytics-app 设置 Django 标签?
- java - 在 for 循环中创建 JTextField 以逐步计算数字的 pow
- python - 无法在 Python 3 和 Jupyter 中导入包