如何检查javascript中是否存在锚标记

时间:2017-05-06 10:49:24

标签: 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{
//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);
      }

    }

1 个答案:

答案 0 :(得分:1)

更新。仍然不确定这是否正是你想要的。您的上述代码似乎工作正常。



//adding polyfill
if (window.Element && !Element.prototype.closest) {
  Element.prototype.closest =
    function(s) {
      var matches = (this.document || this.ownerDocument).querySelectorAll(s),
        i,
        el = this;
      do {
        i = matches.length;
        while (--i >= 0 && matches.item(i) !== el) {};
      } while ((i < 0) && (el = el.parentElement));
      return el;
    };
}

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) => {
    var a = e.target.closest("a");
    if (a && a.getAttribute('href')) {

      global = e.target.closest("a").getAttribute('href');
      console.log(global)
    } else {
      global = e.target.src;
      console.log(global)
    }
    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);
  }

}
&#13;
<a href='example.com'>
  <img src="http://lorempixel.com/400/200" />
</a>
<a>
  <img src="http://lorempixel.com/400/200" />
</a>

<img src="http://lorempixel.com/400/200" />
&#13;
&#13;
&#13;