2010-08-04 124 views
4

我在動態創建的按鈕上附加了onclick事件,但事件未觸發。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); 

} 

回答

2

使用addEventListener

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

init功能沒有內容頁窗上的,所以您不能設置函數的字符串名字。

+0

在你的答案,什麼是「假」部分的目的? – RayB 2014-04-29 21:55:11

+1

@ Rayz321,它與是否使用捕獲或冒泡有關。如果你不確定,你通常應該使用假/冒泡。較新的瀏覽器允許省略第三個參數,但我目前不推薦。 – 2014-04-29 23:37:10

1

我還沒有與GreaseMonkey合作,但我猜你的腳本是在它自己的範圍內,並且在腳本完成運行後釋放它的所有變量。由於你在這個範圍內定義了init,但是在主頁面上調用它,函數在被調用時是未定義的。

你可以把整個功能在onclick事件或觸發回調:

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

(的attachEvent是IE專用)

相關問題