2017-09-23 58 views
1

我正在嘗試運行兩個不同的函數,它們執行兩個單獨的事情。當一個div被點擊時,兩者都需要運行。 div是在JavaScript的innerHTML函數中生成的。使用.innerHTML發送參數到JS函數

這是第二次運行的方法。它需要一個參數,然後在頁面上生成一個div。

//Display larger image: 
function furtherDetails(mainImage){ 
    var moreInfo = document.getElementById('divpropertyInfo'); 
    moreInfo.innerHTML = '<div id="propInfoDisplay">' + 
          '<img id="image" src="'+mainImage+'" alt="Main Image" />' + 
         '</div>'; 
} 

這是一個運行該函數的代碼:

//Create the property div: 
function createPropertyDiv(mainImage, bedrooms, bathrooms, parkings, price, address, latitude, longitude){ 

    var propertyDiv = document.getElementById('divsearchResults'); 
    propertyDiv.innerHTML += '<div id="divResults" onclick="showMap('+latitude+','+longitude+');furtherDetails('+mainImage+');">' + 
           '<img id="mainImage" src="' + mainImage +'" alt="Main Image" />' + 
           '<p id="numBedrooms">'+ bedrooms +'</p>' + 
           '<img id="bedroomsImage" src="/images/bedrooms.png" />' + 
           '<p id="numBathrooms">'+ bathrooms +'</p>' + 
           '<img id="bathroomsImage" src="/images/bathrooms.png" />' + 
           '<p id="numParking">'+ parkings +'</p>' + 
           '<img id="parkingImage" src="/images/carspots.png" />' + 
           '<p id="Price">'+ price +'</p>' + 
           '<p id="addressHeading">Address: </p>' + 
           '<p id="Address">' + address + '</p>' + 
          '</div>'; 
} 

我收到錯誤:

Uncaught SyntaxError: missing) after argument list

+0

當你得到這個錯誤?你點擊的時間? – Farsay

+0

@Christopher我不認爲這兩個函數的錯誤是否可以共享一個顯示錯誤的工作片段,如果可能的話JSFiddle? –

+0

檢查你的函數對'('&')' –

回答

1

onclick的變量需要通過'"包圍,否則他們將在點擊之前進行評估,導致您的語法錯誤。

onclick="showMap(\''+latitude+'\',\''+longitude+'\');furtherDetails(\''+mainImage+'\') 

簡單的例子

let el = document.getElementById('foo'); 
 
let f = "bar"; 
 

 
function bar(c) { 
 
    console.log(c); 
 
} 
 

 
el.innerHTML += '<div onclick="bar(\'' + f + '\')">Baz</div>'; // logs the value of f 
 
el.innerHTML += '<div onclick="bar(' + f + ')">Boo</div>'; // logs the function bar
<div id="foo"> 
 
Foo 
 
</div>

話雖這麼說,不使用內聯的JavaScript。改用eventListener。然後,您可以將任何想要的功能傳遞給函數,而無需擔心轉義,並且可以根據需要從監聽器調用盡可能多的函數。

function foo(bar) { 
 
    console.log(bar); 
 
} 
 
let bar = 'bar'; 
 

 
let el = document.createElement('div'); 
 
el.id = 'resultDiv'; 
 
el.appendChild(document.createTextNode('child')); 
 

 
el.addEventListener('click', function() { 
 
    foo(bar); 
 
}, false); 
 

 
document.getElementById('foo').appendChild(el);
<div id="foo">Foo</div>

0

我認爲這個問題是在這裏

根據你的代碼的HTML將是這樣的 - 你必須使用逃生繩

<div id="divResults" onclick="showMap(1,3);furtherDetails(images/123.jpg);"> 

\ 「和你的html應該是這樣的 -

<div id="divResults" onclick="showMap(1,3); furtherDetails('images/123.jpg');">