How can I pass a variable through an onclick event

2019-07-14 05:34发布

My javascript creates a line of html.

That html has an onclick event call to openSingle().

I need to pass a variable into that function.

onclick="openSingle('+findID+')"

When I check the dev panel when it runs, i get

onclick="openSingle(WP0100200-3a)"

The only thing that is missing is the quotes around the id. But if i try to code in the quotes, it breaks the html and then puts everything out of order.

Here is my line of code and all the pertaining variables.

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle('+findID+')"/>';
var paragraph = '<p id="Manual-para" class="colorMe"><a href="';
var redirect = linkMe + '#' + findID;
var manName = section.childNodes( x ).getAttribute( "manualName" );
var workPack = section.childNodes( x ).getAttribute( "workPacket" );

document.getElementById( "annotateBody" ).innerHTML += iconImage + paragraph + redirect + '">' + annotationTitle + ' - ' + manName + ' - ' + workPack + '</a></p>';

5条回答
SAY GOODBYE
2楼-- · 2019-07-14 06:03

You can escape quotes with a backslash like so

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';

and as other comments suggested you should ideally avoid inline Javascript

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-14 06:06

Escape the single quotes, like this:

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';
查看更多
狗以群分
4楼-- · 2019-07-14 06:12

Here is the answer: with escaping character \ for ' character

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';

Also try concating &lsquo;and&rsquo;

查看更多
看我几分像从前
5楼-- · 2019-07-14 06:13

One thing you could try doing is attach the onclick after you create the DOM node. This lets you be as flexible as you want and avoids having to eval strings and other things like that.

var domnode = /* get the image tag */
domnode.onclick = function(){ openSingle(findId) }
查看更多
你好瞎i
6楼-- · 2019-07-14 06:15

try adding \' will fix the problem

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';
查看更多
登录 后发表回答