最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onclick passing numbers and strings - Stack Overflow

programmeradmin2浏览0评论

When I put a string value into an onclick the console returns 'Uncaught SyntaxError: Unexpected token ILLEGAL'? It works fine if its just a number but not if its a string!

Code:

document.getElementById("productMenu").innerHTML += "<div class=\"leftMenuItems\"    onclick=\"javascript:showResources(" + p_codes + ");\">" + p_codes + " - " + p_names + "</div>";

<div class="leftMenuItems" onclick="javascript:showResources(1234ABC);">Product Name</div>

When I put a string value into an onclick the console returns 'Uncaught SyntaxError: Unexpected token ILLEGAL'? It works fine if its just a number but not if its a string!

Code:

document.getElementById("productMenu").innerHTML += "<div class=\"leftMenuItems\"    onclick=\"javascript:showResources(" + p_codes + ");\">" + p_codes + " - " + p_names + "</div>";

<div class="leftMenuItems" onclick="javascript:showResources(1234ABC);">Product Name</div>
Share Improve this question edited Mar 29, 2012 at 9:00 Nicola Peluchetti 76.9k32 gold badges149 silver badges195 bronze badges asked Mar 29, 2012 at 8:57 Mr FishMr Fish 451 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

You are missing quotes

onclick="javascript:showResources('1234ABC');"

because 1234ABC is a string, while numbers don't need quotes

The problem is that if you don't wrap the argument in quote marks, JavaScript is looking for a variable of the same name. Since variable names cannot begin with number literals, you're receiving the error. Numbers alone will be passed in as integers.

You should use the following:

<div class="leftMenuItems" onclick="javascript:showResources('1234ABC');">Product Name</div>

Try this, it worked for me.

Pass string inside of quote in the following string.format: HttpUtility.HtmlEncode("'"+personnelPhotoList[j].name.Trim()+"'")

Code sample:

StringBuilder strPhotos = new StringBuilder();

strPhotos.Append(String.Format("<div class=\"div_employee_img\">
         <a href=\"#\" onclick=\"DeletePhoto({0}); return true;\"></a></div>,   
         HttpUtility.HtmlEncode("'"+personnelPhotoList[j].name.Trim()+"'")));

Somehow it did not post plete code, here it is again

strPhotos.Append(String.Format("<input type=\"button\" onclick = \"Delete({0}) return false;\", HttpUtility.HtmlEncode("'"+personnelPhotoList[j].name.Trim()+"'")));

发布评论

评论列表(0)

  1. 暂无评论