开发者

Passing parameters to a function in an onclick event

I'm trying to dynamically build some HTML and assign a function to the onclick event of a link. Here's the code I've got...

link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = function(){someFunction(myObject.id);};
link.appendChild(document.createTextNode("Click Me!"));

My research has indicated that I wrap my function call within an anonymous function like I have done. What I'm finding though is that my function is called when this bit of script runs instead of on the click event. This seems to be a common problem but I'm following all the advice I've found so far but开发者_开发知识库 to no avail.

Any help or pointers is much appreciated.

Mister B.


Maybe try this alternative method:

function someFunction(id) {
    return function() {
        alert(id);
    };
}

link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = someFunction(myObject.id);
link.appendChild(document.createTextNode("Click Me!"));


The code you've posted works fine - I just tested it. Here are some possibilities to look for..

  1. Where have you defined someFunction? Is it being called upon definition?
  2. Do you reference someFunction anywhere else? Perhaps that is what is triggering the issue.
  3. Any reason you're not using a javascript library like jQuery to do this? Simplifies a lot.

One debugging method would be to change that line to:

link.onclick = function(){alert('test'); someFunction(myObject.id);};

Is the alert popping up? My guess is not, suggesting #1 and #2 above. Feel free to post more code and we can look for the error elsewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜