Javascript 无法在 jsf 中单击按钮时获取正确的 id



我在运行时遇到此错误。我不知道为什么它显示document.getElementById(...(为空。它的引用方式有任何问题。我已经阅读了很多,但仍然无法寻找解决方案。任何小小的帮助也会得到承认。谢谢。

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

缩进.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: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 id="formId">
                <p:inputTextarea  rows="15" cols="80" id="text1"></p:inputTextarea>
                <br/>
                <h:commandButton  type="button" value = "submit" action="indentation" onclick="myFunction()"></h: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}
            };
            function myFunction() {
                let indent = 0;
                document.getElementById('formId:demo').innerHTML = document.getElementById('formId:text1').value.split(/[rn]+/).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/>");
            }
            window.onload = myFunction;
        </script>
</html>

拜托,谁能帮我找到这里的问题?按下按钮后,它应该为代码提供一些颜色。

你需要获取元素的子元素 - 所以使用 querySelector .

document.querySelector("#formId #demo")

最新更新