如果一个网页不是以HTML/JavaScript形式呈现,可以前往其他链接。

7
在 HTML 或 JavaScript 中,是否有任何选项,使得当用户点击链接时,如果该链接可用,则打开该链接,如果不可用,则打开另一个链接。
以下是我的部分代码:
<div id="sidebar-collapse" class="col-sm-3 col-lg-2 sidebar">
 <ul>
    <li><a href="/returns"><span class="glyphicon glyphicon-log-in"></span> Returns</a></li>
    <li  class="active"><a href="/pay_reco" target="_blank"><span class="glyphicon glyphicon-log-in"></span> Payment Recouncillation </a></li>
    <li ><a href="/pay_get" target="_blank"><span class="glyphicon glyphicon-log-in"></span> Payment Get </a></li>
    <li><a href="/import"><span class="glyphicon glyphicon-log-in"></span> Import </a></li>
    <li>

<!-- Here I want to add  Two link in a href tag if first link does not 

available (web page not available) then it go to another link
        <!-- <object data="http:/127.0.0.1:9004" type="href" > -->
        <a target="_blank" href="http://127.0.0.1:9001">
            <span class="glyphicon glyphicon-log-in"></span>
             ComPare
        </a>
    </li>
    <li><a target="_blank" href="http://127.0.0.1:9000"><span class="glyphicon glyphicon-log-in"></span> Portal </a></li>


为什么要在文档中放置无效链接指向自己的网站? - Jaromanda X
你能否在你的代码中添加一些注释,以解释你发布的代码与你所提出的问题有何关联? - Jaromanda X
@JaromandaX 我只是在尝试,如果可能的话怎么做?如果不行也没关系。 - Shubham Batra
3
@user - 几乎任何事情都是可能的。 - Jaromanda X
@JaromandaX,是的,我同意你的看法。希望我们能找到解决方案。 - Shubham Batra
显示剩余5条评论
1个回答

5

步骤1:按如下方式更新您的HTML代码。

<a id="selector" href="javascript:void(0)">
            <span class="glyphicon glyphicon-log-in"></span>
             ComPare
</a>

步骤2:在更新您的HTML后,使用jQuery处理点击事件并发送ajax请求,如果响应正常,则转到链接1,否则您需要路由到另一个URL。

$(function(){
    $('body').on('click', '#selector', function() {
        $.ajax({
            type: "GET",
            url: "http://127.0.0.1:9001",    
            complete: function(xhr, textStatus) {
               if(xhr.status == 200) window.location = "http://127.0.0.1:9001";
               else window.location = "http://127.0.0.1:9004";
            } 
        });
    })
})

我为这种情况创建了一个小的jQuery插件,在这里可以找到。

使用AnotherJS:

HTML:

<a href="http://127.0.0.1:9001" data-another="http://127.0.0.1:9004">Link Text</a>

Javascript:

$(function() {
   $('a').another();
})

这就是全部啦! :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接