我想從單擊的HTML文檔中的單擊元素中獲取某個innerText。如何從單擊元素的相關節點獲取innerHTML/innerText?
相應的HTML看起來是這樣的:
!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<ul class="categories">
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>First</span>
</div>
</a>
</li>
<li>
<a href="http://www.example2.com/1">
<div>
<img src="http://www.example.com/someSource">
<span>Second</span>
</div>
</a>
</li>
</ul>
</body>
</html>
一個JavaScript函數應該取決於點擊鏈接返回要麼「第一」或「第二」。
我的基本想法是添加事件偵聽器,並使用返回的事件獲得跨度元素的內容:
function(){
document.addEventListener('click', function(e) {
e = e || window.event;
var spanText= e.path[i].innerText; //Don't know how to assign i correctly
return spanText;
}, false);
}
我的問題是,我不知道如何定義我或如果有什麼比.path [i]更適合使用。取決於我是否點擊圖片或文字。
會發生什麼,如果圖像用戶點擊? – Rounin
@Rounin我是修正代碼 – Smiranin