2013-05-15 18 views
-1

我不知道爲了我的生活。如何在Firefox中使用element.onclick?

我動態創建的元素,我需要一個點擊事件添加到它,雖然它需要在所有瀏覽器的工作一直到IE7。

var bottle = document.createElement('a'); 
bottle.id = 'target'; 
bottle.onclick = function(){makeClickable();}; 
//bottle.setAttribute('onclick', 'makeClickable();'); 
bottle.setAttribute('title', 'Lavender'); 
bottle.setAttribute('class', 'lavenderButton'); 
bottle.setAttribute('style', '**MY STYLES**'); 
bottle.innerHTML = "<div class='button pulse lavenderBottleImg'><img width='100%' src='**SOURCE**' class='indicator'></div>"; 
document.body.appendChild(bottle); 

Here's a JSFiddle。它被稍微修改:makeClickable()被定義爲向JavaScript控制檯輸出消息,並且div內的圖像元素被替換爲文本。

onclick的作品,但不是在Firefox!如何讓onclick在所有瀏覽器上工作?

註釋掉選項沒有在IE7的工作(這一點很重要它在那裏工作!),要麼添加事件監聽器沒有工作。

唷!做這件事的正確方法是什麼?因爲你擁有它

+0

你得到一個錯誤或沒有任何反應呢? – Nomad101

+0

考慮使用'addEventListener'進行事件綁定https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener –

+0

根本沒有錯誤。不做任何事 –

回答

2

onclick事件工作正常。我剛剛運行它,使用alert()而不是makeClickable()。這表明問題不在於你編寫click事件的方式,而在於makeClickable()中的某些內容。

Proof

相關問題