简体   繁体   English

JavaScript'myFunction'不是函数,即使它是

[英]JavaScript 'myFunction' is not a function, even though it is

I've something like 我有类似的东西

let myFunction;
$(document).ready(function() {
    myFunction = function(param) {
        // ...
    }
});

and inside my HTML, I have 在我的HTML中,

<a href="javascript:void(0);" onclick="myFunction(1)">...</a>

Now it says Uncaught ReferenceError: myFunction is not defined . 现在说Uncaught ReferenceError: myFunction is not defined

 let myFunction; $(document).ready(function() { myFunction = function(param) { console.log('running'); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="javascript:void(0);" onclick="myFunction(1)">...</a> 

OK, so what I tried was: 好的,所以我尝试的是:

$(document).ready(function() {
    function myFunction(param) {
        // ...
    }
});

but again, Uncaught ReferenceError: myFunction is not defined . 但是同样, Uncaught ReferenceError: myFunction is not defined I've no idea, really, I used the first piece of code for a long time now and all of a sudden, that doesn't work anymore (or not in my context, or what ever). 我不知道,实际上,我很长时间以来一直在使用第一段代码,突然之间,它不再起作用了(或者在我的上下文中不可用,或者发生了什么)。 What's the correct approach to this? 正确的方法是什么?

I created a JSFiddle to show that what I tried doesn't work indeed (expected output is 1 or 2 in an alert, error given): https://jsfiddle.net/kgdcwe4z/5/ 我创建了一个JSFiddle来表明我尝试的确实不起作用(警报中的预期输出为1或2,给出了错误): https : //jsfiddle.net/kgdcwe4z/5/

Better to do only with Jquery like this below: 最好只对Jquery进行如下操作:

<a href="javascript:void(0);" data-id="1" id="test">...</a>

$(document).ready(function() {
    $("#test").on('click', function() {
       const id = $(this).attr('data-id');
       //doSomething considering the id as the param here
    });
});

Another solution with only Javascript is: 仅使用Javascript的另一种解决方案是:

const myFunction = function(param) {
    // ...
}

<a href="javascript:void(0);" onClick="myFunction(1)">...</a>

With your existing code, you can achieve like this with closure: 使用您现有的代码,可以使用闭包来实现以下目的:

$(document).ready(function() {
    func = function(param) {
  console.log('param => ', param)
  }
})(func);

Updated answer link: https://jsfiddle.net/cjnp40e6/ 更新的答案链接: https : //jsfiddle.net/cjnp40e6/

Just move the function into the global scope. 只需将函数移到全局范围即可。

// outside of $(document).ready(function() { ...
function myFunction(param) {
    // ...
}

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

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