我的 HTML 页面上有以下链接,所有链接标记之间都有不同的 URL 和不同的文本。
<a onmouseover="myFunction()" class="green" href="url.com">word here</a>
myFunction 是一个显示单词定义的脚本。我只需要弄清楚如何得到这个词。
我想获取鼠标悬停在其上的单词,而不是具有“绿色”类的标签之间页面上的其他单词。有什么方法可以获取标签之间的当前单词我的鼠标悬停在上面?
最佳答案
只需将节点传递给函数即可:
<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);
}
或者,如果您愿意,也可以简单地传递文本:
<a onmouseover="myFunction(this.innerText || this.textContent)" class="green" href="url.com">word here</a>
这允许您的函数直接访问文本:
myFunction(elementText){
console.log('the text is: ' + elementText);
}
不过,更好的是从内联处理程序中删除事件处理,如果只是为了方便更新/维护,请使用以下方法:
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>
正如下面的评论所指出的,没有必要将函数调用包装在匿名函数中,而是允许像这样调用:
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;
}
或者可能:
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 中不起作用,它使用 attachEvent()
代替 addEventListener()
,但如果没有 IE,我无法进行实验/改进了 IE 兼容性。)
顺便说一句,我使用了 body
因为它是唯一的祖先元素,将事件绑定(bind)到最接近 的祖先元素的性能更高(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;
}
引用文献:
关于javascript - 如何获取鼠标悬停在其上的链接的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15437499/