2017-09-23 44 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');">