【问题标题】:Uncaught ReferenceError: jQuery is not defined (Thymeleaf)未捕获的 ReferenceError:未定义 jQuery(Thymeleaf)
【发布时间】:2021-06-29 19:12:13
【问题描述】:

嗨,所以我有一个学校项目,我剩下的唯一问题是“找不到 jquery”错误。我已经为此苦苦挣扎了 5 天,我不知道如何解决它。我第一次在这个项目中使用 srping boot、thymeleaf、html/css/js 和 jquery。该代码应该显示一个动态服务图表,并且用户应该填写它(您测试 html 以查看它)。这是我的代码(我从 github 复制粘贴:https://github.com/caprica/jquery-orgchart):

<!DOCTYPE html>
    <!--suppress ALL -->
    <html lang="en" xmlns:th="https://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Service Chart</title>
    
        <link href="/static/css/jquerysctipttop.css" th:href="@{/css/jquerysctipttop.css}" rel="stylesheet" type="text/css">
        <link type="text/css" href="/static/css/jquery.orgchart.css" media="all" rel="stylesheet" th:href="@{/css/jquery.orgchart.css}" />
        <Style type="text/css">
            body{
                background: rgb(52, 73, 94);
                font-family: "Alegreya Sans ", sans-serif;
                text-align-all: center;
            }
            h1{
                color:  white;
                text-align: center;
                text-transform: uppercase;
                font-size: 40px;
            }
            #orgChart{
                width: auto;
                height: auto;
            }
    
            #orgChartContainer{
                /* width: 1500px;
               /*  height: 500px;*/
                overflow: auto;
                background: #aef0e1;
            }
            button{
                background: #93cdaa;
                margin: 20px auto 20px 40px;
                text-align: center;
                font-size: 20px;
                padding: 10px 10px;
                border: 2px solid #143b22;
                outline: none;
                color: #212d3a;
                border-radius: 24px;
                transition: 0.25s;
                cursor: pointer;
            }
            button[name='return']{
                background: rgba(176, 2, 17, 0.63);
                color: white;
            }
    
            button:hover{
                border-color: #aef0ca;
                background: #426a54;
                color: white;
                margin-bottom: 20px;
    
            }
            button[name= 'return']:hover{
                border-color: rgb(22, 35, 52);
                background: rgba(176, 2, 17, 0.95);
                margin-bottom: 20px;
            }
    
        </style>
    
        <script type="text/javascript" th:src="@{http://code.jquery.com/jquery-3.5.1.min.js}"></script>
        <script type="text/javascript" th:src="@{/js/jquery.min.js}"> </script>
    
    </head>
    
    <body>
        <h1 style="margin-top:50px">Fill the chart according to the characteristics
            <br> of your new service:</h1>
    
        <a href="AdminMenu.html" th:href="@{/AdminMenu}">
            <button name="return">Return</button>
        </a>
    
        <form class="box" action="#" method="post" th:action="@{/ModServiceForm}">
            <div id="orgChartContainer">
                <button type="submit" onclick="alert('Tree saved.')" name="finish">Save Tree</button>
                <div id="orgChart">Here</div>
            </div>
        </form>
    
        <div id="consoleOutput">
        </div>
    
        <script type="text/javascript" th:src="@{/js/jquery.orgchart.js}"></script>
        <script type="text/javascript">
            console.log("I'm inside js.");
            var $jq = jQuery.noConflict(true );
    
            let testData = [
                {id: 1, name: 'My service',nomResp:'#',prenomResp:'#',contactResp:'#'
                    ,emailResp:'#',cible: '#',datain:'#',dataout:'#',priorite:'#',bdd:'#'
                    , parent: 0}];
    
            $(document).ready(function(){
                console.log("I'm inside the function.");
                let org_chart = $("#orgChart").orgChart({
                    data: testData,
                    showControls: true,
                    allowEdit: true,
                    onAddNode: function (node) {
                        console.log('Created new node on node ' + node.data.id);
                        org_chart.newNode(node.data.id);
                    },
                    onDeleteNode: function (node) {
                        console.log('Deleted node ' + node.data.id);
                        org_chart.deleteNode(node.data.id);
                    },
                    onClickNode: function (node) {
                        console.log('Clicked node ' + node.data.id);
    
                        let dataout = org_chart.getData();
    
                        $.ajax({
                            type: "POST",
                            url: "#",
                            data: 'dataout=' + dataout,
                            dataType: "json"
                        });
    
    
                        console.log('Heres the data so far: (id,name, nomResp, prenomResp,' +
                            'contact, email, cible, datain, dataout, priorite,' +
                            'bdd)\n');
    
                        for (let i = 0; i < dataout.length; i++) {
                            let string = "\n" + dataout[i].id + ", " + dataout[i].name + ", " +
                                dataout[i].nomResp + ", " + dataout[i].prenomResp
                                + ", " + dataout[i].emailResp + ", " + dataout[i].contactResp
                                + ", " + dataout[i].cible + ", " + dataout[i].datain + ", " +
                                dataout[i].dataout + ", " + dataout[i].priorite
                                + ", " + dataout[i].bdd + ", " + dataout[i].parent + "\n";
    
                            console.log(i + "-->" + string + "\n");
                        }
                    }
                });
                console.log("I left the function.");
            } );
    
    
        </script>
    
    
    </body>
    </html>

我把 .min 脚本放在头部,就像一些教程推荐的那样。我还使用 $(document).ready 来确保它正确加载,甚至还有一个中文教程推荐使用 var $jq = jQuery.noConflict(true) 这是我一直在猜测的错误: ModServiceForm:92 Uncaught ReferenceError: jQuery is not defined at ModServiceForm:92 当我删除该行 (92: var $jq=jquery.noConflict(true)) 我得到另一个错误说 Uncaught ReferenceError: $ is not defined at ModServiceForm:99 (带有 $ document.ready 的行(函数)))

我是这个东西的新手,我真的不知道该怎么做。我正在使用 IntelliJ IDEA 2021.1.2(终极版)

idk 如果这也需要,但这里是 jquery.orgchart.js 文件:

(function($) {
    $.fn.orgChart = function(options) {
        let opts = $.extend({}, $.fn.orgChart.defaults, options);
        return new OrgChart($(this), opts);        
    }

    $.fn.orgChart.defaults = {
        data: [{id:1, name:'Root',nomResp:'nomResp',prenomResp:'prenomResp',contactResp:'contactResp',emailResp:'emailResp',cible: 'cible',datain:'datain',dataout:'dataout',priorite:'priorite',bdd:'bdd'
            , parent: 0}],
        showControls: false,
        allowEdit: false,
        onAddNode: null,
        onDeleteNode: null,
        onClickNode: null,
        newNodeText: 'Add Child'
    };

    function OrgChart($container, opts){
        let data = opts.data;
        let nodes = {};
        let rootNodes = [];
        this.opts = opts;
    //    this.$container = $container;
        let self = this;

        this.draw = function(){
            $container.empty().append(rootNodes[0].render(opts));
            $container.find('.node').click(function(){
                if(self.opts.onClickNode !== null){
                    self.opts.onClickNode(nodes[$(this).attr('node-id')]);
                }
            });

            if(opts.allowEdit){
                $container.find('.node h2').click(function(e){
                    let thisId = $(this).parent().attr('node-id');
                    self.startEdit(thisId);
                    e.stopPropagation();
                });
            }

            // add "add button" listener
            $container.find('.org-add-button').click(function(e){
                let thisId = $(this).parent().attr('node-id');

                if(self.opts.onAddNode !== null){
                    self.opts.onAddNode(nodes[thisId]);
                }
                else{
                    self.newNode(thisId);
                }
                e.stopPropagation();
            });

            $container.find('.org-del-button').click(function(e){
                let thisId = $(this).parent().attr('node-id');

                if(self.opts.onDeleteNode !== null){
                    self.opts.onDeleteNode(nodes[thisId]);
                }
                else{
                    self.deleteNode(thisId);
                }
                e.stopPropagation();
            });
        }

        this.startEdit = function(id){
            let inputElement = $('<input class="org-input" placeholder="Name" type="text" value="'+nodes[id].data.name+'"/>' );
            let inputNomResp = $('<input class="org-input" placeholder="Nom Responsable" type="text" value="'+nodes[id].data.nomResp+'"/>' );
            let inputPrenomResp = $('<input class="org-input" placeholder="Prenom Responsable" type="text" value="'+nodes[id].data.prenomResp+'"/>' );
            let inputEmailResp = $('<input class="org-input" placeholder="Email Responsable" type="email" value="'+nodes[id].data.emailResp+'"/>' );
            let inputContactResp = $('<input class="org-input" placeholder="Contact Responsable" type="text" value="'+nodes[id].data.contactResp+'"/>' );
            let inputCible = $('<input class="org-input" placeholder="Cible" type="text" value="'+nodes[id].data.cible+'"/>' );
            let inputDatain = $('<input class="org-input" placeholder="Data in" type="text" value="'+nodes[id].data.datain+'"/>' );
            let inputDataout = $('<input class="org-input" placeholder="Data out" type="text" value="'+nodes[id].data.dataout+'"/>' );
            let inputPriorite = $('<input class="org-input" placeholder="Priorité" type="text" value="'+nodes[id].data.priorite+'"/>' );
            let inputBDD = $('<input class="org-input" placeholder="BDD" type="text" value="'+nodes[id].data.bdd+'"/>' );

            $container.find('div[node-id='+id+'] h2[id="name"]').replaceWith(inputElement);
            $container.find('div[node-id='+id+'] h2[id="nomResp"]').replaceWith(inputNomResp);
            $container.find('div[node-id='+id+'] h2[id="prenomResp"]').replaceWith(inputPrenomResp);
            $container.find('div[node-id='+id+'] h2[id="email"]').replaceWith(inputEmailResp);
            $container.find('div[node-id='+id+'] h2[id="contact"]').replaceWith(inputContactResp);
            $container.find('div[node-id='+id+'] h2[id="cible"]').replaceWith(inputCible);
            $container.find('div[node-id='+id+'] h2[id="datain"]').replaceWith(inputDatain);
            $container.find('div[node-id='+id+'] h2[id="dataout"]').replaceWith(inputDataout);
            $container.find('div[node-id='+id+'] h2[id="priorite"]').replaceWith(inputPriorite);
            $container.find('div[node-id='+id+'] h2[id="bdd"]').replaceWith(inputBDD);

            let commitChange = function(){
                let h2Element = $('<h2 id="name">'+nodes[id].data.name+'</h2>');
                let h2ElementnomResp= $('<h2 id="nomResp">'+nodes[id].data.nomResp+'</h>');
                let h2ElementprenomResp= $('<h2 id="prenomResp">'+nodes[id].data.prenomResp+'</h2>');
                let h2ElementcontactResp= $('<h2 id="contact">'+nodes[id].data.contactResp+'</h2>');
                let h2ElementemailResp= $('<h2 id="email">'+nodes[id].data.emailResp+'</h2>');
                let h2Elementcible= $('<h2 id="cible">'+nodes[id].data.cible+'</h2>');
                let h2Elementdatain= $('<h2 id="datain">'+nodes[id].data.datain+'</h2>');
                let h2Elementdataout= $('<h2 id="dataout">'+nodes[id].data.dataout+'</h2>');
                let h2Elementpriorite= $('<h2 id="priorite">'+nodes[id].data.priorite+'</h2>');
                let h2Elementbdd= $('<h2 id="bdd">'+nodes[id].data.bdd+'</h2>');

                if(opts.allowEdit){
                    h2Element.click(function(){
                        self.startEdit(id);
                    })
                    h2ElementnomResp.click(function(){
                        self.startEdit(id);
                    })
                    h2ElementprenomResp.click(function(){
                        self.startEdit(id);
                    })
                    h2ElementemailResp.click(function(){
                        self.startEdit(id);
                    })
                    h2ElementcontactResp.click(function(){
                        self.startEdit(id);
                    })
                    h2Elementcible.click(function(){
                        self.startEdit(id);
                    })
                    h2Elementdatain.click(function(){
                        self.startEdit(id);
                    })
                    h2Elementdataout.click(function(){
                        self.startEdit(id);
                    })
                    h2Elementpriorite.click(function(){
                        self.startEdit(id);
                    })
                    h2Elementbdd.click(function(){
                        self.startEdit(id);
                    })
                }
                    inputElement.replaceWith(h2Element);
                    inputNomResp.replaceWith(h2ElementnomResp);
                    inputPrenomResp.replaceWith(h2ElementprenomResp);
                    inputContactResp.replaceWith(h2ElementcontactResp);
                    inputEmailResp.replaceWith(h2ElementemailResp);
                    inputCible.replaceWith(h2Elementcible);
                    inputDatain.replaceWith(h2Elementdatain);
                    inputDataout.replaceWith(h2Elementdataout);
                    inputPriorite.replaceWith(h2Elementpriorite);
                    inputBDD.replaceWith(h2Elementbdd);
            }

            /*inputElement.focus();
            inputNomResp.focus();
            inputPrenomResp.focus();
            inputContactResp.focus();
            inputEmailResp.focus();
            inputCible.focus();
            inputDatain.focus();
            inputDataout.focus();
            inputPriorite.focus();
            inputBDD.focus();*/

            inputElement.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.name = inputElement.val();
                }
            });
            inputElement.blur(function(){
                commitChange();
            })
            inputNomResp.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.nomResp = inputNomResp.val();
                }
            });
            inputNomResp.blur(function(){
                commitChange();
            })
            inputPrenomResp.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.prenomResp = inputPrenomResp.val();
                }
            });
            inputPrenomResp.blur(function(){
                commitChange();
            })
            inputContactResp.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.contactResp = inputContactResp.val();
                }
            });
            inputContactResp.blur(function(){
                commitChange();
            })
            inputEmailResp.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.emailResp = inputEmailResp.val();
                }
            });
            inputEmailResp.blur(function(){
                commitChange();
            })
            inputCible.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.cible = inputCible.val();
                }
            });
            inputCible.blur(function(){
                commitChange();
            })
            inputDatain.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.datain = inputDatain.val();
                }
            });
            inputDatain.blur(function(){
                commitChange();
            })
            inputDataout.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.dataout = inputDataout.val();
                }
            });
            inputDataout.blur(function(){
                commitChange();
            })
            inputPriorite.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.priorite = inputPriorite.val();
                }
            });
            inputPriorite.blur(function(){
                commitChange();
            })
            inputBDD.keyup(function(event){
                if(event.which === 13){
                    commitChange();
                }
                else{
                    nodes[id].data.bdd = inputBDD.val();
                }
            });
            inputBDD.blur(function(){
                commitChange();
            })

        }

        this.newNode = function(parentId){
            let nextId = Object.keys(nodes).length;
            while(nextId in nodes){
                nextId++;
            }

            self.addNode({id: nextId, name: 'service x',nomResp:'',prenomResp:'',contactResp:'',emailResp:'',cible: '',datain:'',dataout:'',priorite:'',bdd:''
                , parent: parentId});
        }

        this.addNode = function(data){
            let newNode = new Node(data);
            nodes[data.id] = newNode;
            nodes[data.parent].addChild(newNode);

            self.draw();
            self.startEdit(data.id);
        }

        this.deleteNode = function(id){
            for(let i=0;i<nodes[id].children.length;i++){
                self.deleteNode(nodes[id].children[i].data.id);
            }
            nodes[nodes[id].data.parent].removeChild(id);
            delete nodes[id];
            self.draw();
        }

        this.getData = function(){
            let outData = [];
            for(let i in nodes){
                outData.push(nodes[i].data);
            }
            return outData;
        }

        // constructor
        for(let i in data){
            nodes[data[i].id] = new Node(data[i]);
        }

        // generate parent child tree
        for( let i in nodes){
            if(nodes[i].data.parent === 0){
                rootNodes.push(nodes[i]);
            }
            else{
                nodes[nodes[i].data.parent].addChild(nodes[i]);
            }
        }

        // draw org chart
        $container.addClass('orgChart');
        self.draw();
    }

    function Node(data){
        this.data = data;
        this.children = [];
        let self = this;

        this.addChild = function(childNode){
            this.children.push(childNode);
        }

        this.removeChild = function(id){
            for(let i=0;i<self.children.length;i++){
                if(self.children[i].data.id === id){
                    self.children.splice(i,1);
                    return;
                }
            }
        }

        this.render = function(opts){
            let childLength = self.children.length,
                mainTable;

            mainTable = "<table cellpadding='0' cellspacing='0' border='0'>";
            let nodeColspan = childLength>0?2*childLength:2;
            mainTable += "<tr><td colspan='"+nodeColspan+"'>"+self.formatNode(opts)+"</td></tr>";

            if(childLength > 0){
                let downLineTable = "<table cellpadding='0' cellspacing='0' border='0'><tr class='lines x'><td class='line left half'></td><td class='line right half'></td></table>";
                mainTable += "<tr class='lines'><td colspan='"+childLength*2+"'>"+downLineTable+'</td></tr>';

                let linesCols = '';
                for(let i=0;i<childLength;i++){
                    if(childLength===1){
                        linesCols += "<td class='line left half'></td>";    // keep vertical lines aligned if there's only 1 child
                    }
                    else if(i===0){
                        linesCols += "<td class='line left'></td>";     // the first cell doesn't have a line in the top
                    }
                    else{
                        linesCols += "<td class='line left top'></td>";
                    }

                    if(childLength===1){
                        linesCols += "<td class='line right half'></td>";
                    }
                    else if(i===childLength-1){
                        linesCols += "<td class='line right'></td>";
                    }
                    else{
                        linesCols += "<td class='line right top'></td>";
                    }
                }
                mainTable += "<tr class='lines v'>"+linesCols+"</tr>";

                mainTable += "<tr>";
                for(let i in self.children){
                    mainTable += "<td colspan='2'>"+self.children[i].render(opts)+"</td>";
                }
                mainTable += "</tr>";
            }
            mainTable += '</table>';
            return mainTable;
        }

        this.formatNode = function(opts){
            let nameString = '',
                nomRespString = '',
                prenomRespString = '',
                emailString = '',
                contactString = '',
                cibleString = '',
                datainString = '',
                dataoutString = '',
                priorteString = '',
                bddString = '',
                descString = '';
            let buttonsHtml;
            if(typeof data.name !== 'undefined'){
                nameString = '<h2 id="name">'+self.data.name+'</h2>';
            }
            if(typeof data.nomResp !== 'undefined'){
                nomRespString = '<h2 id="nomResp">'+self.data.nomResp+'</h>';
            }
            if(typeof data.prenomResp !== 'undefined'){
                prenomRespString = '<h2 id="prenomResp">'+self.data.prenomResp+'</h2>';
            }
            if(typeof data.emailResp !== 'undefined'){
                emailString = '<h2 id="email">'+self.data.emailResp+'</h2>';
            }
            if(typeof data.contactResp !== 'undefined'){
                contactString = '<h2 id="contact">'+self.data.contactResp+'</h2>';
            }
            if(typeof data.cible !== 'undefined'){
                cibleString = '<h2 id="cible">'+self.data.cible+'</h2>';
            }
            if(typeof data.datain !== 'undefined'){
                datainString = '<h2 id="datain">'+self.data.datain+'</h2>';
            }
            if(typeof data.dataout !== 'undefined'){
                dataoutString = '<h2 id="dataout">'+self.data.dataout+'</h2>';
            }
            if(typeof data.priorite !== 'undefined'){
                priorteString = '<h2  id="priorite">'+self.data.priorite+'</h2>';
            }
            if(typeof data.bdd !== 'undefined'){
                bddString = '<h2 id="bdd">'+self.data.bdd+'</h2>';
            }
            if(typeof data.description !== 'undefined'){
                descString = '<p>'+self.data.description+'</p>';
            }
            if(opts.showControls){
                buttonsHtml = "<div class='org-add-button'>"+opts.newNodeText+"</div><div class='org-del-button'></div>";
            }
            else{
                buttonsHtml = '';
            }
            return "<div class='node' node-id='"+this.data.id+"'>"+nameString+nomRespString
                +prenomRespString+contactString+emailString+cibleString+datainString
                +dataoutString+priorteString+bddString+descString+ buttonsHtml+"</div>";
        }
    }

})(jQuery);

【问题讨论】:

  • 您是否尝试过在文档加载之前不运行 jQuery 代码?
  • 抱歉 - 我看到你确实有 jQuery - 我错过了。
  • 我添加了 $document.ready() 以确保 jquery 函数在文档加载之前不会运行,但它会在 $ 处停止,表示它无法识别它
  • 您提到您正在使用var $jq = jQuery.noConflict(true );。这意味着您对 jQuery 的所有调用现在都需要使用$jq 而不是通常的$。但是在定义$jq 之后,你可以继续使用$ 这里:$(document).ready(function(){...。因此,要么 (a) 将此(以及所有类似的 jQuery $ 用法)更改为 $jq(document).ready(function(){...。或者,(b) 注释掉 noConflict 行。只有当有另一个库也希望使用$,与 jQuery 冲突时,您才需要它。这可能无法解决您的所有问题 - 可能还有其他问题隐藏...
  • 哦,我不知道,谢谢...当它不起作用时,我已经删除了该行,但我在此处留下评论以表明我已经对其进行了测试..谢谢,我会保留它为未来着想!

标签: javascript html jquery thymeleaf orgchart


【解决方案1】:

终于成功了(我想我需要把它贴在这里以获得启发??) 我所做的是进入我的 cmd 管理模式并确保我确实安装了 jquery,所以我输入:npm install jquery 以防万一。然后我打开了一个新页面,除了:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me to hide paragraphs</button>

</body>
</html>

看看我是否会得到任何错误。然后我补充说: &lt;script th:src="@{https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js}"&gt;&lt;/script&gt; 放在头上,然后我把我所有的脚本放在头上(按照这个顺序),最后把 css 放在后面。 我觉得有点傻,因为我花了 5 天时间?。感谢任何花时间阅读和评论我的问题的人!真的非常感谢你^^。

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 2013-06-29
    • 2019-01-23
    • 2014-04-12
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多