简体   繁体   English

将参数传递给函数。 怎么了?

[英]Passing argument to function. What's wrong?

In this jsFiddle 在这个jsFiddle中

am I trying to pass an argument to a function, but it doesn't receive the argument or it isn't executed. 我试图将一个参数传递给一个函数,但它没有收到参数或者它没有被执行。

<a href="javascript:addRemove('7249');">Details</a>

JQuery JQuery的

$(document).ready(function() {

    function addRemove(u) {
    alert(u);
    }

});

Any ideas what's wrong and how to fix it? 任何想法有什么问题以及如何解决它?

您的函数仅存在于ready事件处理程序的范围内,您需要在ready函数之外移动函数addRemove。

http://jsfiddle.net/EcCTx/2/ http://jsfiddle.net/EcCTx/2/

Your code was wrapped in an onload event by jsfiddle (drop-down menu on the left). 您的代码被jsfiddle (左侧的下拉菜单)包含在onload事件中。 So if you add a function it won't be global, but your onclick event calls a global function by the name addRemove . 因此,如果添加一个函数,它将不是全局函数,但是您的onclick事件通过名称addRemove调用全局函数。

您需要在$(document).ready()之外定义您的函数。

addRemove函数必须在$(document).ready(function(){...});

I haven't tested it, but my guess is this: things inside of a function can't be accessed from outside of a function. 我没有测试过,但我的猜测是这样的:函数内部的东西无法从函数外部访问。 For example, 例如,

$(document).ready(function() {
    function addRemove(u) {
        alert(u);
    }
});
console.log(addRemove); // reference error or something similar

You should define addRemove function outside of $(document).ready . 您应该 $(document).ready 之外定义addRemove函数。

You had no defined function called addRemove in the Fiddle! 你没有在小提琴中定义的名为addRemove的函数!

I've added this, and removed the inline javascript calls. 我添加了这个,并删除了内联的JavaScript调用。

See this for better way of doing it: 看到这个以获得更好的方法:

http://jsfiddle.net/EcCTx/6/ http://jsfiddle.net/EcCTx/6/

In case Davin doesn't come back, here's the answer: jsFiddle defaults to wrapping your JS in the 'onLoad' method - and we can't allow that. 如果Davin没有回来,这就是答案:jsFiddle默认将JS包装在'onLoad'方法中 - 我们不能允许这样做。

http://jsfiddle.net/nqbWe/ http://jsfiddle.net/nqbWe/

There is nothing specifically calling that function. 没有什么专门调用这个功能。 In the document ready part you have the function set up, but the anchor will not call that function by itself. 在文档就绪部分中,您已设置了功能,但锚点本身不会调用该功能。 In this instance it will only be called when someone clicks on that link. 在这种情况下,只有在有人点击该链接时才会调用它。

You could give the link a class and data attribute and use those with jQuery to have something happen on page load. 你可以给链接一个类和数据属性,并使用jQuery来在页面加载时发生一些事情。

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

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