简体   繁体   中英

Uncaught syntax error when passing an object to a function in javascript

I have the following function which has a button and when clicking the button it triggers another function.

function navbar(id,CSVdata) {
        if(CSVdata){
           console.log('CSVdata',CSVdata)
           return `<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                    <a id="downloadcsv${id}" class="dropdown-item" href="#" onclick="downloadCSV(${id},${CSVdata})">Download CSV</a>
                   </div>
            `;
        }
 }

function downloadCSV(id,data) {
    console.log("downloadcsv",data);
}

The thing is when i console my CSVdata data it's showing correctly in the console. When i try to pass it to my downloadCSV function i'm getting an error as Uncaught SyntaxError:Unexpected identifier and the passed object is shown as downloadCSV(lc,[object Object]) What could be the issue here? I tried stringifying the object but still the same error.

To pass the object to the inline handler, you'll have to serialize it for the HTML markup. But this is extremely ugly. Inline handlers are bad practice (due in part to the problems you're experiencing) - there's no real reason to use them nowadays. Instead, add the listener properly with JavaScript and addEventListener :

function navbar(id,CSVdata) {
    if(!CSVdata) return;
    const fragment = new DocumentFragment();
    fragment.innerHTML = `
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <a id="downloadcsv${id}" class="dropdown-item" href="#">Download CSV</a>
        </div>
    `;
    fragment.querySelector('a').addEventListener('click', () => {
        downloadCSV(id, CSVdata);
    });
    return fragment;
}

I think you're trying to pass an object as an argument into an inline JavaScript function call. I highly recommend trying something else because there's almost certainly a better way but if you want to try it, you can encode the object as a JSON string before you combine it into the html code.

function navbar(id,CSVdata) {
        if(CSVdata){
           console.log('CSVdata',CSVdata)
           return `<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                    <a id="downloadcsv${id}" class="dropdown-item" href="#" onclick='downloadCSV(${id},${JSON.stringify(CSVdata)})'>Download CSV</a>
                   </div>
            `;
        }
 }

function downloadCSV(id,data) {
    console.log("downloadcsv",data);
}

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