简体   繁体   中英

JavaScript: variable name unresolved

I wrote the following JS code:

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

I get an error for the line:

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

It seems that JS can't resolve the variable 'dataItems' inside the -tag:

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

However, later in the same line, JS resolves successfully the same name for the part:

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

What do you think can be the problem? How can I make dataItems be resolved inside the -tag ?

Your variable is inside a string. Try changing the code to:

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

In this line

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

unless dataItems is a global variable, it won't be available to the environment which will make this call downloadFile(dataItems[r]) , since onclick event will be invoked in a global scope.

You need to bind the event less intrusively this way

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

As you're placing a string inside the element's attribute it is not recognized as a JavaScript code or a JavaScript function so place the JavaScript function itself.

So you can do, var anchor = '<a href="#" onclick="' + your_func_here + '"></a>';

A sample example illustrating the problem, in this example if you write the function name as a string in the onclick property the function won't be called.

 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> 

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