greasemonkey将onclick事件添加到按钮

cou*_*011 5 javascript greasemonkey

我在动态创建的按钮上附加了onclick事件,但事件未触发.

var ind = location.href.indexOf('http://www.example.com/');
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); 

}
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 4

使用addEventListener

elem.addEventListener('click', init, false);
Run Code Online (Sandbox Code Playgroud)

您的init函数未在内容页面窗口中定义,因此您无法将函数名称设置为字符串。