开发者

Uncaught ReferenceError: doit is not defined

I'm writing a small userscript to include a link next to user's profile image for a phpBB forum that I frequent. On clicking the link, I'm getting an error like below:

Uncaught ReferenceError: doit is not defined
(anonymous function)            viewtopic.php:542
onclick                         viewtopic.php:543

Portion of the userscript:

(function(){

    var script = doc开发者_StackOverflowument.createElement('script');
    script.textContent = '(' + twk.toString() + ')();';
    document.body.appendChild(script);

    function twk() {

        pd = document.getElementsByClassName('postdetails');

        for (i=0 ; i<(pd.length); i++) {
            ele = document.createElement("a");
            ele.innerHTML ='<a href=\'#\' onclick=\'doit();\'>Quick reply</a>';

            pd[i].appendChild(ele);

        }

   function  doit() {
        selec = document.getSelection().anchorNode.textContent;
        document.getElementsByClassName("row2").item('message').innerHTML = selec;

    }

}




})();

Can anyone please point out where/what am I doing wrong?


First of all, you're creating your element all wrong. It should be like this:

var link = document.createElement('a');
link.setAttribute('href', '#');
link.innerHTML = 'New text';

And to add an event to it:

link.onclick = doit

Finally, add it to the page like you're doing:

pd[i].appendChild(ele);

You might want to consider using a framework like jQuery or Mootools, it will make your life much easier. Sometimes there are conflicts with browsers doing stuff like that. I personally like Mootools, but jQuery is easier to pick up, especially for small projects.

EDIT:

I added the innerHTML to the example. I would just use a framework instead of doing this the hard way though.


unwrap everything from that outer anon function and it should work:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜