2013-10-14 119 views
0

這裏是我的腳本的一部分:有什麼不對這個js功能?

function create(panel_id,iframe_source,handle_title) { 
var temp1=document.createElement("a"); 
temp1.setAttribute("href","#"); 
var attr=document.createAttribute("onClick"); 
attr.nodeValue="showPanel(panel_id)"; 
temp1.setAttributeNode(attr); 
temp1.className="controller"; 
temp1.innerHTML=handle_title; 
div.appendChild(temp1); 
} 
function showPanel(panel_id) { 
var elem = document.getElementById(panel_id); 
elem.classList.toggle("show"); 
} 

而這裏就是我所說的第一個功能部分:

<a href="#" onClick="create('test','http://example.com','example')">create</a> 

當我稱呼它,每一個元素都正確地創建和除工作的的onClick attribute.I注意到,當我改變這樣的功能:

... 
attr.nodeValue="showPanel('test')"; 
... 

一切工作fine..Can有人告訴我,我做了什麼錯誤的PLZ?

+0

放在一個的jsfiddle和張貼的鏈接。 –

+1

'「showPanel(」 + panel_id +「)」;'應該工作 - 可以執行該函數,其中'panel_id'不再作爲一個局部變量,使用字符串連接固定到位 – SmokeyPHP

+2

該值你最好用'temp1.onclick =函數(){showPanel(panel_id)};'。 – VisioN

回答

6

變化:

attr.nodeValue="showPanel(panel_id)"; 

到:

attr.nodeValue="showPanel('" + panel_id + "')"; 
+0

它的工作!感謝ü非常多,但你能解釋一下這個解決方案? 「+ foo +」做什麼? – user2879198

+0

@ user2879198你是作爲傳遞的參數變量名稱,而不是變量的值。 – Jonathan

+0

@ user2879198哦,如果一切正常,你應該接受的答案是正確的;) – Jonathan

0

有兩個問題

1)的onClick應的onclick

2)"showPanel(panel_id)";

"showPanel('" + panel_id + "')"; 

試試這個

function create(panel_id,iframe_source,handle_title) { 
var temp1=document.createElement("a"); 
temp1.setAttribute("href","#"); 
var attr=document.createAttribute("onclick"); 
attr.nodeValue="showPanel('" + panel_id + "')"; 
temp1.setAttributeNode(attr); 
temp1.className="controller"; 
temp1.innerHTML=handle_title; 
div.appendChild(temp1); 
} 
function showPanel(panel_id) { 
var elem = document.getElementById(panel_id); 
elem.classList.toggle("show"); 
} 
+0

這工作太course..Thank你 – user2879198

+0

歡迎您 – Dhaval