簡體   English   中英

JavaScript:變量名未解析

[英]JavaScript: variable name unresolved

我編寫了以下JS代碼:

function downloadFile(dataItem) {
    ....
}
....
for (var r = 0; r < dataItems.length ; r++) {
    table += '<tr>';
    var listOfAttributes = ['CarModel', 'BusMapping', 'Date_', 'Location_', 'Comments', 'AttackTraffic', 'IsTagged']
    **table +='<td> <a onclick="downloadFile(dataItems[r])" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';**
    for (var c = 0; c < Object.keys(dataItems[0]).length-1 ; c++) {
        table +='<td>' + dataItems[r][listOfAttributes[c]]["S"] +'</td>';
    }
    table+= '</tr>'
}

我收到一條錯誤消息:

table +='<td> <a onclick="downloadFile(dataItems[r])" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';

似乎JS無法解析-tag中的變量'dataItems':

<a onclick="downloadFile(dataItems[r])" href="#">.

但是,稍后在同一行中,JS成功解析了零件的相同名稱:

+ dataItems[r]['FileName']['S'] +

您認為可能是什么問題? 如何使dataItems在-tag中解析?

您的變量在字符串中。 嘗試將代碼更改為:

table +='<td> <a onclick="' + downloadFile(dataItems[r]) + '" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';**

在這條線

<a onclick="downloadFile(dataItems[r])" href="#">

除非dataItems是全局變量,否則它將無法用於進行調用downloadFile(dataItems[r]) ,因為onclick事件將在全局范圍內調用。

您需要以這種方式減少對事件的綁定

//you need to update the selector as per your markup
document.querySelector ( "tr td a" ).addEventListener( "click", function(){
  downloadFile(dataItems[r]);
})

當您在元素的屬性內放置字符串時,它不會被識別為JavaScript代碼或JavaScript函數,因此請將JavaScript函數本身放置。

這樣就可以了, var anchor = '<a href="#" onclick="' + your_func_here + '"></a>';

一個示例問題的示例,在此示例中,如果您在onclick屬性中將函數名稱寫為字符串,則不會調用該函數。

 var container = document.getElementById('container'); var element = document.createElement('a'); element.href = '#'; element.text = 'Fire!'; element.onclick = fire; // this invokes the fire function // element.onclick = 'fire'; // this won't invoke the fire function container.appendChild(element); function fire() { console.log('fired'); } 
 <div id="container"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM