当javascript创建html时,如何通过onclick事件传递变量? [英] How can I pass a variable through an onclick event when javascript is creating the html?

查看:320
本文介绍了当javascript创建html时,如何通过onclick事件传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JavaScript创建了一行html.

My javascript creates a line of html.

该html具有对openSingle()的onclick事件调用.

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

唯一缺少的是id周围的引号. 但是,如果我尝试在引号中编写代码,则会破坏html,然后使所有内容乱序.

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

和其他评论一样,理想情况下,您应该避免使用内联Javascript

and as other comments suggested you should ideally avoid inline Javascript

这篇关于当javascript创建html时,如何通过onclick事件传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆