Simple jquery function not working

This simple function does not work. Display next error

'myfunc' undefined

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    function myfunc(){
      alert('In');
    }
  })
</script>
<button type="button" onclick="myfunc()">Alert</button>
Run codeHide result
+4
source share
6 answers

This is a realm problem, myfunc is not in the global realm. When you put it inside $(document).ready(), you can only call it in a callback document.ready().

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  //this doesn't need to be in document.ready(), it won't get called until button is already loaded anyway
  function myfunc() {
    alert('In');
  }
</script>
<button type="button" onclick="myfunc()">Alert</button>

You can learn more about how scope works in JS at http://www.w3schools.com/js/js_scope.asp

+6
source

, , . , DOM. , .

, . , . document.ready (), DOM.

+2

$(document).ready(function() {
  $("#btn").click(function() {
    alert('Button Clicked')
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="btn">Alert</button>
Hide result

. -

+1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>   $(document).ready(function(){
function myfunc(){
  alert('In');
}   });/*don't forget ;*/ 
</script> <button type="button" onclick="myfunc()">Alert</button>
0

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    function myfunc(){
      alert('In');
    }
  $(document).ready(function(){
    
  })
</script>
<button type="button" onclick="myfunc();">Alert</button>
Hide result
0

JavaScript: myfunc "onload" jquery.

- "onload" - (a() - "onload" , b() - myfunc()):

var b; // without this line it would still work, since
       // b would implicitely become a global variable in a()
function a(){
    // function b(){ ... would *not* work here
    b=function(){
      alert('In');
    }
}
a();
b();

Now, getting back to your real problem: the solution provided by @guradio is by far the best way to move forward using jquery so that it is used.

0
source

Source: https://habr.com/ru/post/1666694/


All Articles