简体   繁体   中英

Javascript function fails to be called when passed with an argument

I have a div, which onclick calls a javascript function. But it fails to do so when i call the javascript with an argument in it. This is very weird.

This below code calls the function deals() on clicking the button 'deals'

$("#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

$("#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. If it is, then you need to declare the variable first.

So this would depend on where this javascript is placed. 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);
$("#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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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