简体   繁体   English

带参数传递时无法调用Javascript函数

[英]Javascript function fails to be called when passed with an argument

I have a div, which onclick calls a javascript function. 我有一个div,onclick调用了javascript函数。 But it fails to do so when i call the javascript with an argument in it. 但是,当我调用带有参数的javascript时,它无法执行此操作。 This is very weird. 这很奇怪。

This below code calls the function deals() on clicking the button 'deals' 下面的代码在单击“交易”按钮时调用函数deal()

$("#content").append('<div class="malldetails"><a href="javascript:void(0);"><button class="left" onclick="deals()">Deals</button></a></div>');

function deals(){
alert("This works");
}

But the code below doesn't work. 但是下面的代码不起作用。

$("#content").append('<div class="malldetails"><a href="javascript:void(0);"><button class="left" onclick="deals(mallName)">Deals</button></a></div>');

function deals(NameOfMall){
alert("This does not work");
}

I believe it should be a small problem, but just not able to figure it out. 我认为这应该是一个小问题,但无法解决。 Please help me out Brilliant coders! 请帮助我,出色的编码器! thanks a lot! 非常感谢!

You have to use quotes around mallName 您必须在mallName周围使用引号

$("#content").append('<div class="malldetails"><a href="javascript:void(0);"><button class="left" onclick="deals(\'mallName\')">Deals</button></a></div>');

function deals(NameOfMall){
    alert("This does not work");
}

如果在触发该onclick时未定义mallName (我怀疑是),则不会发生警报。

Turn on the javascript error on your borwser (if using IE) and see if it is showing error. 打开浏览器上的JavaScript错误(如果使用IE),然后查看它是否显示错误。 If it is, then you need to declare the variable first. 如果是,那么您需要先声明该变量。

So this would depend on where this javascript is placed. 因此,这取决于此javascript的放置位置。 What shows up in the code, the error is due to the variable not defined. 代码中显示的内容是由于未定义变量引起的。

您的代码正在运行。.检查mallName是否已初始化。.可能未定义。

onclick="deals("Lechmere Mall")" //wont work. 

Check with 检查与

onclick="deals(\'Lechmere Mall\')" //will work.

Its working fine. 它的工作正常。

Check whether mallName is initialized using alert. 检查是否使用alert初始化mallName。

alert(mallName);
$("#content").append('<div class="malldetails"><a href="javascript:void(0);">
<button class="left" onclick="deals(mallName)">Deals</button></a></div>');

function deals(NameOfMall){
alert("This does not work");
}

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

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