JavaScript Error: Uncaught TypeError: foo is not a function

后端 未结 3 733
半阙折子戏
半阙折子戏 2021-01-25 01:56

For some reason JavaScript doesn\'t seem to recognise my function.

I have a button in some HTML:

相关标签:
3条回答
  • 2021-01-25 01:58

    The problem is you give to your element the same id : "lightOn". In this scope lightOn is the element, which shadows the function (read more).

    A simple solution would be to give a different id to the element or a different name to the function.

    A better one would be to separate the script from the HTML:

    <button type="button" class="btn btn-default" id="lightOn">On</button>
    
    $(function(){
        $('#lightOn').click(function() {
            $("#lightOn").addClass("active");
            $("#lightOff").removeClass("active");
            socket.emit("setting", {"light":"on"});
        });
    });
    
    0 讨论(0)
  • 2021-01-25 02:05

    Try this:

    var lightOn = function(){
    
    }
    

    And you can do all of this in vanilla JS instead of using jQuery too:

    var lightOn = function(){
        document.getElementById('lightOn').className += " active";
        document.getElementById('lightOff').className.replace(/\bactive\b/,'');
        socket.emit("setting", {"light":"on"});
    }
    

    A good explanation for var lightOn = function() and function lightOn() can be found here: https://stackoverflow.com/a/336868/1887101

    0 讨论(0)
  • 2021-01-25 02:23

    Instead of using the onclick attribute, it is much cleaner to add the event listener in JavaScript, like so:

    $('#lightOn').on('click', function() {
      $("#lightOn").addClass("active");
      $("#lightOff").removeClass("active");
      socket.emit("setting", {"light":"on"});
    });
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button type="button" class="btn btn-default" id="lightOn">On</button>

    0 讨论(0)
提交回复
热议问题