user2879198
user2879198

Reputation: 75

What is wrong with this js function?

Here is a part of my script:

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

And here is the part where I call the first function:

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

When I call it, every element is created correctly and working except for the onClick attribute.I noticed that when I change the function like this:

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

everything is working fine..Can someone tell me what I have done wrong plz?

Upvotes: -1

Views: 98

Answers (2)

Dhaval
Dhaval

Reputation: 2861

there are two problems

1) onClick should be onclick

2) "showPanel(panel_id)"; should be

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

try this

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

Upvotes: 0

Jonathan
Jonathan

Reputation: 773

Change:

attr.nodeValue="showPanel(panel_id)";

to:

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

Upvotes: 6

Related Questions