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

喜你入骨 提交于 2019-12-11 02:18:33

问题


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

回答1:


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




回答2:


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+'\')"/>';



回答3:


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+'\;)"/>';



回答4:


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:


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


来源:https://stackoverflow.com/questions/13585280/how-can-i-pass-a-variable-through-an-onclick-event-when-javascript-is-creating-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!