2014-09-10 26 views
2
<a class="lnk" href="#" onclick="showItem();"> 
    <span data-id="27">TEST</span> 
</a> 

function showItem() 
{ 
    var itid = event.target.dataset.id; 
    alert(itid); 
} 

如果試圖this jsfiddle code你可以看到,IE(11)和Chrome事件對象被正確評估,但與Firefox(32.0),你會得到一個錯誤(ReferenceError:event is not defined)事件對象不是(IE和Chrome的工作)

這是Firefox或IE和Chrome中不同事件對象生命週期的錯誤? 但是,因爲在IE和Chrome中它工作,我認爲這是一個問題。 關於解決方法?

PS:在的jsfiddle,只用Firefox,代碼選擇仍然有問題(一些運行之後,你不能選擇的代碼

回答

11

你應該通過event作爲參數傳遞給函數:

<a class="lnk" href="#" onclick="showItem(event);"> 
    <span data-id="27">TEST</span> 
</a> 

function showItem(e) 
{ 
    e = e || window.event; 
    var itid = e.target.dataset.id; 
    alert(itid); 
} 

訪問它作爲一個全局變量是Chrome複製的IE功能,但我不認爲它是標準的Javascript。

+0

好的作品,但問題的一部分是:爲什麼在IE和Chrome的作品沒有傳遞事件?他們隱式地通過它? – Luca 2014-09-10 21:47:34

+1

他們有一個設置爲當前事件的全局變量。 – Barmar 2014-09-10 21:48:46

+0

好的,問題的那一部分的答案在這裏http://stackoverflow.com/questions/7457260/event-target-not-working-on-firefox – Luca 2014-09-10 21:49:14

相關問題