2014-10-17 73 views
0

我試圖傳遞一個對象到一個按鈕的onclick,但它似乎並沒有工作。這就是我想:傳遞對象到onclick

<input type='button' onclick='showTransreqForm(\"" + result.productsArray[i] + "\")' value='Go'> 

如果我打印的對象,result.productsArray[i],僅高於這條線,我可以看到它在JavaScript控制檯中的所有屬性。

但是,當我在showTransreqForm函數中打印它時,它來作[object Object]和數據似乎並不存在。

剛剛完成,這是showTransreqForm功能:

function showTransreqForm(plan) { 
    console.log(plan); 
} 

我缺少什麼?

編輯:這是生成該按鈕的一部分的代碼:

var planStr = "<b>Recommended Plans</b>" + "<br><br>" + 
    "<form id='getTransForm' method='POST'>"; 
    for (i = 0; i < result.productsArray.length; i++) { 
     console.log(result.productsArray[i]); 
     console.log(result.productsArray[i].get("Price")); 

     planStr += "plan " + (i+1) + "<br>" + 
     result.productsArray[i].get("CarrierName") + ": " + 
     result.productsArray[i].get("Price") + 
     "<input type='button' value='Go' onclick='showTransreqForm(\"" + result.productsArray[i] + "\")' >" + 

     "<br><br>"; 
    } 
    planStr += "</form>"; 
    $(".success3").append('<br />' + planStr).show(); 

如以上所提到的,result.productsArray[i]打印正確從內部的for循環中,也是如此,價格屬性。但它不能正確傳遞到showTransreqForm函數。

+0

'result'從哪裏來? – 2014-10-17 09:02:49

+0

來自Parse.com雲代碼。換句話說,從服務器。 – Eddy 2014-10-17 09:04:26

+1

你可以在服務器上顯示代碼嗎?我認爲這是範圍問題 – 2014-10-17 09:06:47

回答

1

這是因爲您構建onclick的方式。將字符串附加到對象將導致字符串。
在你的情況下,「」+對象會導致「[object Object]」。
你的代碼只需更改下面

<input type='button' onclick='showTransreqForm(result.productsArray[i])' value='Go' 

我假設你已經在全球範圍定義結果變量。

+0

我編輯了代碼塊的問題。基本上我不能只使用你提供的代碼行,因爲這個按鈕是動態生成的字符串的一部分。 – Eddy 2014-10-17 09:53:59

+0

只需綁定索引i而不是result.productsArray [i]。在接收事件時,您只需將參數解析爲int並將其與result.productsArray一起使用即可。 – Amitesh 2014-10-17 10:01:17

+0

謝謝。我確實必須在全局範圍內定義它,然後將全局變量設置爲結果,並傳遞索引。 – Eddy 2014-10-17 10:22:09