Onclick with argument causes javascript syntax error

- 1 answer

Ad

I got the "Uncaught SyntaxError: Unexpected identifier" when clicking element that goes by id "elem". Can you please tell me how to fix this ?

formulaireDB.allDocs({
    include_docs: true
}).then(function(result) {

    for (x in result.rows) {
        docFeature = result.rows[x].doc;
        coord_nv = [docFeature.geometry.coordinates[0], 
                    docFeature.geometry.coordinates[1]];
         position = to3857(coord_nv);

        map.addOverlay(new ol.Overlay({
            position: ol.proj.transform(
                [docFeature.geometry.coordinates[0],
                docFeature.geometry.coordinates[1]],
                'EPSG:4326',
                'EPSG:3857'),
                 element: $('<img id="elem" onclick="clickmarker(' 
                           + result + ',' + x  + ')" src="./img/pin32.png">')
        }));
    }
}).catch(function(err) {
    console.log(err);
});

}

function clickmarker(rt, ind) {
    var res = rt.rows[ind].doc.geometry.coordinates;
    console.log(res);
}
Ad

Answer

Ad

You are concatenating result to a string and loses its value as an object in this line:

element: $('<img id="elem" onclick="clickmarker(' + result + ',' + x  + ')" src="./img/pin32.png">')

You may need to add the click listener after it's been created rather than in-line.

Something such as

element: $('<img...>').on('click',function(){ clickmarker(result,x); });
Ad
source: stackoverflow.com
Ad