![](/img/trans.png)
[英]how to pass a variable function to an onclick event in javascript?
[英]How can I pass a variable through an onclick event when javascript is creating the html?
我的 javascript 創建了一行 html。
該 html 有一個 onclick 事件調用openSingle()
。
我需要將一個變量傳遞給該函數。
onclick="openSingle('+findID+')"
當我在運行時檢查開發面板時,我得到
onclick="openSingle(WP0100200-3a)"
唯一缺少的是id
周圍的引號。 但是,如果我嘗試在引號中編碼,它會破壞 html,然后將所有內容都打亂。
這是我的代碼行和所有相關變量。
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>';
你可以像這樣用反斜杠轉義引號
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';
並且正如其他評論所建議的那樣,您最好避免內聯 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+'\;)"/>';
這是答案:使用轉義字符 \\ for ' 字符
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';
也可以嘗試連接‘
和’
您可以嘗試做的一件事是在創建 DOM 節點后附加 onclick。 這讓您可以隨心所欲地靈活,並避免必須對字符串和其他類似的東西進行求值。
var domnode = /* get the image tag */
domnode.onclick = function(){ openSingle(findId) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.