简体   繁体   English

onclick和外部js文件

[英]onclick and external js file

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

js js

 function play(){
    do something; 
 }

The above works if js code is in the same file as p 如果js代码与p在同一文件中,则以上方法适用

But saying: 但是说:

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

index.js index.js

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

What i get is ReferenceError: play is not defined 我得到的是ReferenceError: play is not defined

Other functions, except play() works well. 除了play()以外的其他功能都play()正常工作。

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

play() function is local to $(document).ready(function(){ not global 玩()函数是local$(document).ready(function(){不是global

Don't wrap your play function in $(document).ready(function(){ to keep it's scope global . 不要将您的play函数包装在$(document).ready(function(){以保持其作用域为global。

function play(){
    do something; 
}

Read Global and Local and Private Functions (Javascript) 阅读全局,本地和私有函数(JavaScript)

and What is the scope of variables in JavaScript? JavaScript中变量的范围是什么?

This is due to scope. 这是由于范围。

play() isn't visible at that level, due to it being wrapped inside your $(document).ready function. play()在该级别不可见,因为它包装在$(document).ready函数中。

No need to place it in $(document).ready( function() {..} 无需将其放在$(document).ready( function() {..}

just mention it in your index.js as 只是在index.js提到它

function play(){
  do something; 
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM