如何检查javascript中是否存在锚定标记
我试图只在锚定标记存在时才为锚定标记的链接分配一个变量,如果锚定标记不存在,则分配其他变量如何检查javascript中是否存在锚定标记,javascript,Javascript,我试图只在锚定标记存在时才为锚定标记的链接分配一个变量,如果锚定标记不存在,则分配其他变量 var global; document.getElementById("img").onmouseover=function(e){ var link=e.target.closest("a").getAttribute('href'); //if link exists then assign the value to global if(link){ global=link; } else{ //
var global;
document.getElementById("img").onmouseover=function(e){
var link=e.target.closest("a").getAttribute('href');
//if link exists then assign the value to global
if(link){
global=link;
}
else{
//do something else
}
我这样做了,但只会导致其他情况。我应该怎么做才能做到这一点。
注意:请仅使用javascript,不要使用jquery
完整代码:
var isHovered = false;
var global;
const imgs = document.getElementsByTagName('img');
const map = fn => x => Array.prototype.map.call(x, fn);
map(img => {
img.addEventListener('mouseover', (e) => {
if(e.target.closest("a").getAttribute('href')){
global=e.target.closest("a").getAttribute('href');
}
else{
global=e.target.src;
}
hoveredBox();
});
img.addEventListener('mouseleave', (e) => {
isHovered=false;
});
})(imgs)
document.addEventListener('keypress', keyDown);
function hoveredBox() {
isHovered = true;
}
function keyDown(event) {
if (!isHovered) return;
var key = event.keyCode;
if(key === 115) {
alert(global);
}
}
更新。仍然不确定这是否正是你想要的。您上面的代码似乎工作正常
//添加多边形填充
if(window.Element&!Element.prototype.closest){
元素=
职能{
var matches=(this.document | | this.ownerDocument).querySelectorAll,
我
el=这个;
做{
i=长度;
而(-i>=0&&matches.item(i)!==el{};
}而((i<0)&(el=el.parentElement));
返回el;
};
}
var isHovered=错误;
var全球;
const imgs=document.getElementsByTagName('img');
const map=fn=>x=>Array.prototype.map.call(x,fn);
映射(img=>{
img.addEventListener('mouseover',(e)=>{
var a=e.目标最近(“a”);
if(a&&a.getAttribute('href')){
global=e.target.closest(“a”).getAttribute('href');
console.log(全局)
}否则{
全局=e.target.src;
console.log(全局)
}
hoveredBox();
});
img.addEventListener('mouseleave',(e)=>{
isHovered=错误;
});
})(imgs)
文件。添加的文件列表器(“按键”,向下键);
函数hoveredBox(){
isHovered=正确;
}
功能键控(事件){
如果(!isHovered)返回;
var key=event.keyCode;
如果(键===115){
警报(全球);
}
}
您能显示您的标记吗?否则我们就只能猜测了,对不起,打错了好吧,我加了。你能在锚标签上加个id吗?是只有一个锚定标签还是有几个锚定标签?我正在尝试做一个chrome扩展,所以这取决于网站。不完全是我要找的。我希望img元素位于中我希望该元素的href链接img@UniqueKiddo那我想你所尝试的可能会奏效。让我试一试。。。