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

javascript - onclick and external js file - Stack Overflow

programmeradmin1浏览0评论
<p onclick="play()">abc</p>

js

 function play(){
    do something; 
 }

The above works if js code is in the same file as p

But saying:

<script src="index.js"></script>

index.js

$(document).ready( function() {
     function play() {
        do something; 
     }
});

What i get is ReferenceError: play is not defined

Other functions, except play() works well.

<p onclick="play()">abc</p>

js

 function play(){
    do something; 
 }

The above works if js code is in the same file as p

But saying:

<script src="index.js"></script>

index.js

$(document).ready( function() {
     function play() {
        do something; 
     }
});

What i get is ReferenceError: play is not defined

Other functions, except play() works well.

Share Improve this question edited Oct 15, 2013 at 8:09 Greg 4791 gold badge5 silver badges21 bronze badges asked Oct 15, 2013 at 7:45 qadenzaqadenza 9,30118 gold badges78 silver badges143 bronze badges 2
  • 1 Have you tried removing the $(document).ready(function() {}); if the javascript is within an external file? – Nunners Commented Oct 15, 2013 at 7:48
  • 1 thanks to everyone. solved – qadenza Commented Oct 15, 2013 at 7:51
Add a ment  | 

3 Answers 3

Reset to default 4
$(document).ready(function(){
  function play(){
        do something; 
     }
});

play() function is local to $(document).ready(function(){ not global

Don't wrap your play function in $(document).ready(function(){ to keep it's scope global .

function play(){
    do something; 
}

Read Global and Local and Private Functions (Javascript)

and What is the scope of variables in JavaScript?

This is due to scope.

play() isn't visible at that level, due to it being wrapped inside your $(document).ready function.

No need to place it in $(document).ready( function() {..}

just mention it in your index.js as

function play(){
  do something; 
}

remove $(document).ready( function() {

发布评论

评论列表(0)

  1. 暂无评论