使用 jquery 的方法错误

Method error using jquery

调用我的方法时,我不断在控制台中收到该消息:

Exception while invoking method 'displayAndAddPost' ReferenceError: $ is not defined

但是一切正常,所以我不确定如何正确使用 Jquery 并停止该错误消息。

调用方法如下:

Meteor.methods({

    displayAndAddPost: function(word, counter) {

    var exist = Posts.findOne({word: word})

        if (word == "") {
            console.log("empty")

        }else if(exist != undefined ){
            //console.log(exist._id)
            Posts.update(exist._id, {$inc: {counter: 1}});
            $(".posts_form").hide();
            $(".posts_index").show();   

        }else{
            Posts.insert({
                word: word,
                counter: counter,
                createdAt: new Date()
            });
            $(".posts_form").hide();
            $(".posts_index").show();           
        }       
    }


});

请注意,虽然它说 $ 未定义,但 Jquery 操作仍然有效。

感谢您的帮助。

Meteor 方法代码在客户端和服务器上都执行,但是在服务器上 jQuery 未定义,因为它是一个仅限浏览器的库。

您可以将您的 jQuery 浏览器特定代码包含在 this.isSimulation 部分中,以便仅在客户端 运行 它们。

if(this.isSimulation){
  $(".posts_form").hide();
  $(".posts_index").show();
}

或者,您可能应该将 jQuery 逻辑移出方法,并根据方法执行的结果仅在客户端上执行它。