简体   繁体   中英

How can I pass a variable through an onclick event when javascript is creating the html?

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>';

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

转义单引号,如下所示:

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

尝试添加\\'将解决问题

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

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;

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) }

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