javascript - greasemonkey adding onclick event to button - Stack Overflow

I am attaching onclick event on dynamically created button but the event is not firing.var ind = loca

I am attaching onclick event on dynamically created button but the event is not firing.

var ind = location.href.indexOf('/');
function init(){
    alert('h');
}
if(ind != -1){      
    var elem = document.createElement("input"); 
    elem.id ='btnGumb';
    elem.value = 'Select Check box';
    elem.type = 'button';
    elem.style.position = 'fixed';
    elem.style.left = '0px';
    elem.style.top = '0px';

    //this is not working
    elem.setAttribute('onclick', 'init();');

    //but alert is working:   elem.setAttribute('onclick', 'alert("h");');

    document.body.appendChild(elem); 

}

I am attaching onclick event on dynamically created button but the event is not firing.

var ind = location.href.indexOf('http://www.example./');
function init(){
    alert('h');
}
if(ind != -1){      
    var elem = document.createElement("input"); 
    elem.id ='btnGumb';
    elem.value = 'Select Check box';
    elem.type = 'button';
    elem.style.position = 'fixed';
    elem.style.left = '0px';
    elem.style.top = '0px';

    //this is not working
    elem.setAttribute('onclick', 'init();');

    //but alert is working:   elem.setAttribute('onclick', 'alert("h");');

    document.body.appendChild(elem); 

}
Share Improve this question edited May 14, 2016 at 1:57 Jonathan Eustace 2,48713 gold badges34 silver badges54 bronze badges asked Aug 4, 2010 at 5:57 coure2011coure2011 42.5k87 gold badges225 silver badges361 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Use addEventListener.

elem.addEventListener('click', init, false);

Your init function isn't defined on the content page window, so you can't set the function name as a string.

I haven't worked with GreaseMonkey, but I'm guessing your script is in its own scope and all its variables are released after the script finishes running. Since you're defining init in this scope, but then calling it on the main page, the function is undefined when it's called.

You could put the entire function in the onclick event or trigger a callback:

if (elem.addEventListener) {
  elem.addEventListener('click',init,false);
} else {
  elem.attachEvent('onclick',init);
}

(attachEvent is IE-specific)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742393032a4435393.html

相关推荐

  • javascript - greasemonkey adding onclick event to button - Stack Overflow

    I am attaching onclick event on dynamically created button but the event is not firing.var ind = loca

    4小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信