最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Missing "Use strict" statement - Stack Overflow

programmeradmin6浏览0评论

I am new to coding. I am receiving this error: "Missing "Use strict" statement" in my Javascript code. Here is my code:

$(function(){
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
});

I do not know where to put 'use-strict';. Where do I put the statement?

I am new to coding. I am receiving this error: "Missing "Use strict" statement" in my Javascript code. Here is my code:

$(function(){
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
});

I do not know where to put 'use-strict';. Where do I put the statement?

Share Improve this question edited Jan 14, 2016 at 22:58 Barmar 784k57 gold badges548 silver badges660 bronze badges asked Jan 14, 2016 at 22:54 JyanJyan 531 gold badge1 silver badge9 bronze badges 5
  • This is optional, it shouldn't cause an error. – Barmar Commented Jan 14, 2016 at 22:56
  • 2 See stackoverflow./questions/1335851/… – Barmar Commented Jan 14, 2016 at 22:57
  • You don't need the leading $. – Mathemats Commented Jan 14, 2016 at 22:57
  • @Mathemats Yes he does, that's how you run the code in the jQuery document.ready handler. – Barmar Commented Jan 14, 2016 at 22:58
  • That's not a JavaScript error, but linter error. – Michał Perłakowski Commented Jan 16, 2016 at 7:30
Add a ment  | 

2 Answers 2

Reset to default 3

As Barmar said, the use strict is optional, but if you had to place it somewhere the best place I would say you should put it is

$(function(){
    "use strict";
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
});

This is where you have to put it whether you use Jquery or Javascript

(function($){
    "use strict";
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
})(jQuery);
.open{
  display: none;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <button class="nav-toggle">Open</button>
  <div class="main-nav">
    <ul>
      <li>Home</li>
      <li>Contact</li>
    </ul>
  </div>
</div>

Assuming you want to achieve a responsive navbar effect I have added the relevant code to make this easier.

In the jQuery part, I'm creating an anonymous function and passing it the $ sign so you can use it safely without polluting the global scope. "use strict" use is not mandatory but if you want to use place it inside the anonymous function as I did.

发布评论

评论列表(0)

  1. 暂无评论