gpt4 book ai didi

javascript - 引用错误 : myFunction() is not defined

转载 作者:太空宇宙 更新时间:2023-11-04 15:45:39 24 4
gpt4 key购买 nike

我在运行时遇到了这个错误。我不知道为什么它显示 myFunction() 未定义。点击按钮时加载函数的方式是否有问题。

到目前为止,这是我的代码。

indentation.xhtml

  <?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">


<h:head>
<style type="text/css">
.code-str { color: #080;}
.code-elem { color: #f00;}
.code-comment { color: #00f;}
</style>
</h:head>


<h:body>

<h:form>
<p:inputTextarea rows="15" cols="80" id="text1"></p:inputTextarea>
<br/>
<p:commandButton type="button" value = "submit" action="indentation" onclick="myFunction()"></p:commandButton>

<div id="demo"></div>
</h:form>
</h:body>


<script type="text/javascript">
const keywords = {
IF: {style: "code-elem", indent: 4},
ENDIF: {style: "code-elem", indent: -4},
IFLISTING: {style: "code-str", indent: 4},
ENDIFLISTING: {style: "code-str", indent: -4},
VAR: {style: "code-comment", indent: 0},
LISTING: {style: "code-comment", indent: 0}
};

window.onload = function myFunction() {
let indent = 0;
document.getElementById("demo").innerHTML = document.getElementById("text1").value.split(/[\r\n]+/).map(line => {
const oldIndent = indent;
line = line.trim().replace(/###([A-Z]+)(.*?)###/g, (m, keyword, arg) => {
const param = keywords[keyword];
if (!param)
return m;
indent += param.indent;
return `<span class="${param.style}">${m}</span>`;
});
return "&nbsp;".repeat(Math.min(indent, oldIndent)) + line;
}).join("<br/>");
}
</script>
</html>

拜托,任何人都可以帮我找到这里的问题吗?按下按钮后,它应该为代码提供一些颜色。

最佳答案

您的 onclick 属性样式事件处理程序期望找到一个名为 myFunction 的全局变量,但是当您使用这样的命名函数表达式时:

window.onload = function myFunction() {
// ...
};

函数名称不会添加到该表达式出现的范围(除了旧的 IE 损坏版本)

函数 声明 添加到作用域,因此您可以使用声明和赋值:

function myFunction() {
// ...
}
window.onload = myFunction;

我强烈建议放弃 onxyz 属性样式的事件处理程序,尤其是因为它们需要全局函数,而全局命名空间已经人满为患且充满冲突。相反,将您的代码包装在范围构造(IIFE、模块等)中并使用现代事件处理(addEventListener 等)。请注意,如果您在 JSF 页面中通过 id 查找元素,则客户端 ID 不是您提供的 id元素(默认),完整解释在 this question's answers . (感谢 Kukeltje 在评论中向 OP 指出这一点。)

关于javascript - 引用错误 : myFunction() is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56579243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com