检查href是否未定义,如果是true alert smth(没有jQuery)

时间:2016-12-22 21:06:16

标签: javascript html class href

我想检查&#34; href&#34;一个<a>标记是空的,如果它是真的,它应该提醒像#34;网站是不可用的atm&#34;,如果链接是正确的,它应该什么也不做。

HTML

<a onclick="testif();" class="link" href="www.google.com">This Link is defined</a>
<a onclick="testif();" class="link" href="">This Link is undefined</a>

的JavaScript

function testif(){
    if (document.getElementsByClassName("link").getAttribute("href") == ""){
    Alert("Site isn't available")

    }else {

    // if the link is correct, alert nothing
   }
};        

谢谢:)

4 个答案:

答案 0 :(得分:3)

您可能会这样做是通过事件并检查event's target

DEMO

function testif (e) {
  // prevent from actually going to another url, feel free to remove the line
  e.preventDefault();
  // in case of IE 6-8 support
  var target = e.target || e.srcElement;
  if (!target.getAttribute('href')) alert("Site isn't available");
}
<a onclick="testif(event)" class="link" href="www.google.com">This Link is defined</a>
<a onclick="testif(event)" class="link" href="">This Link is undefined</a>

答案 1 :(得分:2)

您可以通过event.target

获取并测试点击的链接

function testif(e) {
  e.preventDefault();
  target = e.target || e.srcElement; // Support for IE6-8
  if (target.getAttribute("href") == "") {
    console.log("Site isn't available")
};
<a onclick="testif(event);" class="link" href="http://www.google.com">This Link is defined</a>
<a onclick="testif(event);" class="link" href="">This Link is undefined</a>

或更短的语法:

function testif(e) {
  e.preventDefault();
  target = e.target || e.srcElement; // Support for IE6-8
  (target.getAttribute("href")) || console.log("Site isn't available")
};

答案 2 :(得分:1)

顾名思义,getElementsByClassName会产生多个元素;他们的href属性的组合永远不会等于空字符串。

答案 3 :(得分:0)

getElementsByClassName返回一个元素集合,你需要遍历每个元素来检查它的href

function testif(){
    var links = document.getElementsByClassName("link");
    for(var i = 0; i < links.length; i++) {
        if (links[i].getAttribute("href") == ""){
            alert('Site isn't available');
            return;
        }
    }
}