2015-12-15 27 views
0

當點擊ID爲「elem」的元素時,我得到了「Uncaught SyntaxError:Unexpected identifier」。你能告訴我如何解決這個問題嗎?帶參數的Onclick導致javascript語法錯誤

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); 
} 
+0

如果你格式化強似這麼多東西到構造函數創建變量來代表它們,然後將它們傳遞它的代碼好一點,你可能趕上了錯誤的更多。它會讓你的生活和其他開發人員的生活更容易 –

回答

0

您串聯result爲字符串,並失去了它的價值在這條線的對象:

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

您可能需要後添加點擊監聽器它已經被創建而不是在線。

一些諸如

element: $('<img...>').on('click',function(){ clickmarker(result,x); }); 
+0

謝謝!這很好的解決了這個問題,但它必須放在單獨一行'$(「#elem」)。on('click',function(){clickmarker(result,x);});'' – AAJ

0

您的捕捉功能後有一個額外的大括號。試試這個:

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); 
 
    // add marker 
 

 
    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); 
 
}

+0

它在開始時缺少一行,我的不好:'function ShowFormulaires(){ ... } '在catch部分後面結束 – AAJ