簡體   English   中英

使用jQuery從CSS href查找服務器名稱

[英]Find server name from CSS href with jQuery

如何使用jQuery或JavaScript將以下服務器路徑分配給變量?

<link rel="stylesheet" href="https://myServer:44301/Some/Path/">

<link rel="stylesheet" href="/core/assets/styles.min.css">
<link rel="stylesheet" href="/Content/Site.css">
<link rel="stylesheet" href="https://myServer:44301/Some/Path/">
<link rel="stylesheet" href="https://anotherServer/Another/Path/">

字符串Some/Path是需要匹配的內容。

為了清楚https://myServer:44301/ ,該變量應包含字符串https://myServer:44301/

您可以嘗試以下方法:

function getHostWithPath(path) {
    var linkNodeList = document.getElementsByTagName('link');
    for (var i = 0 ; i <linkNodeList.length ; i++) {
        var l = document.createElement("a");
        l.href = linkNodeList[i].href;
        /*
        // Usefull properties available in l:
        console.log(l.hostname);
        console.log(l.port);
        console.log(l.pathname);
        console.log(l.hash);
        console.log(l.protocol);
        console.log(l.search); // Query String
        */
        if (l.pathname == path) {
            var re = new RegExp(path + '.*');
            return l.href.replace(re, '');
        }
    }
}

var myHostname = getHostWithPath('/Some/Path');

JQuery可以通過在頁面上運行以下代碼來完成此操作:

var server = $("link[href*='/Some/Path']").attr("href").replace("Some/Path/", "");

它的作用是選擇href包含/ Some / Path的元素,並獲取整個href屬性的文本/值。 然后,它將刪除Some / Path /部分,僅留下https://myServer:44301/ ,然后在變量server進行設置。

片段:

 var server = $("link[href*='/Some/Path']").attr("href").replace("Some/Path/", ""); alert(server); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link rel="stylesheet" href="/core/assets/styles.min.css"> <link rel="stylesheet" href="/Content/Site.css"> <link rel="stylesheet" href="https://myServer:44301/Some/Path/"> <link rel="stylesheet" href="https://anotherServer/Another/Path/"> 

 $(function() { $("link").each(function() { var href = $(this).prop("href"); alert(href); }); }); 
 <!DOCTYPE html> <html> <head> <title>title here</title> <meta charset="utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="/core/assets/styles.min.css"> <link rel="stylesheet" href="/Content/Site.css"> <link rel="stylesheet" href="https://myServer:44301/Some/Path/"> <link rel="stylesheet" href="https://anotherServer/Another/Path/"> </head> <body> <!-- page content --> </body> </html> 

下面的代碼獲取每個鏈接,並使用alert()顯示它們。 根據您的條件,我讓您用條件bloc if()來包裝alert()以獲取正確的href(也許您的鏈接總是這樣設置的,所以您希望采用第3個,依此類推)。 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM