ノードを関数に渡すだけです。
<a onmouseover="myFunction(this)" class="green" href="url.com">word here</a>
そして、あなたの機能では:
myFunction(nodeReference){
var text = nodeReference.innerText || nodeReference.textContent;
console.log('the text is: ' + text);
}
JSフィドルデモ。
または、単にテキストを渡すことを好む場合は、次のようにすることができます。
<a onmouseover="myFunction(this.innerText || this.textContent)" class="green" href="url.com">word here</a>
これにより、関数はテキストに直接アクセスできます。
myFunction(elementText){
console.log('the text is: ' + elementText);
}
JSフィドルデモ。
ただし、更新/保守を容易にするためだけに、次のアプローチを使用して、インラインハンドラーからイベント処理を削除することをお勧めします。
function myFunction(nodeReference){
var text = nodeReference.innerText || nodeReference.textContent;
console.log('The text is: ' + text);
}
var As = document.links;
for (var i = 0, len = As.length; i<len; i++){
As[i].onmouseover = function(e){
myFunction(this);
};
}
<a class="green" href="url.com">word here</a>
JSフィドルデモ。
以下のコメントで指摘されているように、関数呼び出しを無名関数でラップする必要はありません。これにより、代わりに次のように呼び出すことができます。
function myFunction(evt){
var text = this.innerText || this.textContent;
console.log('The ' + evt.type + ' text is: ' + text);
}
var As = document.links;
for (var i = 0, len = As.length; i<len; i++){
As[i].onmouseover = myFunction;
}
JSフィドルデモ。
またはおそらく:
function myFunction(nodeReference){
var text = nodeReference.innerText || nodeReference.textContent;
console.log('The text is: ' + text);
}
var body = document.body;
body.addEventListener('mouseover',function(e){
if (e.target.tagName.toLowerCase() == 'a'){
myFunction(e.target);
}
}, false);
(上記は代わりに使用するIEでは機能しませんが、IEattachEvent()
がaddEventListener()
ないと、IEの互換性を実験/改善することはできません。)
JSフィドルデモ。
ちなみに、私はそれが唯一の祖先要素であるためbody
、要素に最も近い祖先要素にイベントをバインドする方がパフォーマンスが高い(CPUの負荷が低い/網羅的ではない)ため、使用しました。想像してみてください、すべてのマウスの動き。)event.target
mouseover
もちろん、準拠したブラウザーでは、CSSを使用できます。
<a class="green" href="url.com" data-definition="The definition of the phrase in this attribute..!">word here</a> <!-- note the custom data-* attribute -->
CSSを使用する場合:
a {
position: relative;
margin: 1em;
}
a:hover::after {
content: attr(data-definition);
position: absolute;
top: 50%;
left: 50%;
color: #000;
background-color: #fff; /* Old IE */
background-color: rgba(255,255,255,0.5);
width: 8em;
border: 1px solid #000;
}
JSフィドルデモ。
参照: