单击超链接时,无法将字符串参数传递给正在调用的简单 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10470680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:27:24  来源:igfitidea点击:

Unable to pass string parameter to a simple Javascript function being invoked when a hyperlink is clicked

javascript

提问by Bhavesh

It's a very simple question but I couldn't figure it out. I'm trying to pass parameters to a Javascript function which is invoked when a hyper link is clicked.

这是一个非常简单的问题,但我无法弄清楚。我正在尝试将参数传递给单击超链接时调用的 Javascript 函数。

It works just fine when the parameters are number but doesn't work when one of them is of type string. I even tried to escape them but unfortunately to no avail.

当参数是数字时它工作得很好,但当其中一个是字符串类型时不起作用。我什至试图逃避他们,但不幸的是无济于事。

The following is a very simple code.

下面是一段非常简单的代码。

function temp(a, b)
{
    alert(a+ "   "+b);
}

<a href="javascript:void(0);" onclick="temp(x, 2);">Click</a>

It doesn't work complaining x is undefinedxis here onclick="temp(x, 2);". When I modify the function something like this temp(1,2);, it works and alerts as specified.

x is undefinedx在这里抱怨是行不通的onclick="temp(x, 2);"。当我修改类似这样的函数时temp(1,2);,它会按照指定的方式工作并发出警报。

What might be the reason? What is the solution?

可能是什么原因?解决办法是什么?

回答by Tobias Krogh

you should avoid passing an undefined variable... xis only a variable as a string starts and end with double or single quotes

您应该避免传递未定义的变量...x只是一个变量,因为字符串以双引号或单引号开头和结尾

function temp(a, b) {
    alert(a+ "   "+b);
}

<a href="javascript:void(0);" onclick="temp('x', 2);">Click</a>

I also created a fiddleto show it works

我还创建了一个小提琴来展示它的工作原理

EDIT: this revision of the fiddle shows that you can also switch the quotes used in the markup... if you are used to double quotes for JS strings fiddle revision 1

编辑:小提琴的这个修订版表明您还可以切换标记中使用的引号...如果您习惯于对 JS 字符串使用双引号fiddle revision 1

回答by gdoron is supporting Monica

<a href="javascript:void(0);" onclick="temp('x', 2);">Click</a>

Demo

演示

With your code, you treat xas it was a variable, while it wasn't decalred, surrond it with quotes.

使用您的代码,您将其x视为一个变量,而它没有被标记,用引号将其包围。



If you want to use the xvariable, declare it about the <a>:

如果要使用该x变量,请将其声明为<a>

<script>
    var x ="foo";

    function temp(a, b) {
        alert(a + "   " + b);
    }?
</script>

<a href="javascript:void(0);" onclick="temp(x, 2);">Click</a>