检查JQuery中的空href属性

时间:2014-03-06 15:58:27

标签: javascript jquery html

我有一个想法,我想实施一个我正在努力的网站。我已经知道它是如何工作的,但我并不完全确定如何将这些碎片拼凑在一起。

所以!!我想检查域名并生成警告框,如果有必要的话。

假设我们有2个域名:

test.domain.com & domain.com

如果我们在 test.domain.com ,并且href (缺失链接)中没有内容,我就会这样做就像一个警告框,弹出说" MISSING LINK"。如果href中有内容,只需忽略它(不缺少链接)

<a href="">Missing Link</a>
<a href="http://google.com">Not Missing Link</a>

然后,如果我们在 domain.com ,我希望jQuery仍然存在于代码中,但如果缺少链接被点击了。因为它只会重定向到主页 - 不是最好的旅程,但比侵入式弹出框要好得多。

这样我可以使用一小段代码来检查测试阶段的丢失链接,但不必在每次发送到实际域时将其删除。

如果其中任何一个没有意义,请询问!

万分感谢,非常感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

$(document).on("click", 'a[href=""]', function(evt) {
    if(window.location.hostname.indexOf("test")!==-1) {
        alert("broken");
    } else {
        window.location.href = "foo.html";
    }
    evt.preventDefault();
});

就个人而言,如果我在测试页面上确定链接是否被破坏,我会做一些事情,这样当页面打开时它们会突出。而不是点击找出来。

if(window.location.hostname.indexOf("test")!==-1) {
    $('a[href=""]').css("background-color", "red");
}

答案 1 :(得分:1)

以下是一些可以帮助您入门的代码。我觉得无论你在尝试什么,我们都采取了错误的方法。

if (location.host === 'test.domain.com' && !$('a[href=""]').length) {
  alert('MISSING LINK');
}

答案 2 :(得分:0)

怎么样?

$(document).ready(function() {
  $('a').click(function(e) {
    var a = $(this);
    e.preventDefault();
    if($.trim(a.prop('href')) == "")
    {
        alert("No link")
    }
    else   
    {
        window.location = $.trim(a.prop('href'));
    }
  }); 
});