找出链接来自外部网站或域名所属的主机。通过Javascript或Jquery

找出链接来自外部网站或域名所属的主机。通过Javascript或Jquery,javascript,jquery,Javascript,Jquery,如果需要找出的链接是来自外部网站 例如:如果图像链接是 然后需要显示外部图像 elseimage.jpg则需要显示内部图像 为此,我生成了如下代码 var img= https://static.scientificamerican.com/sciam/cache/file/268F292B-5DDD-4DB1-B5ABC6541A70ECDF.jpg; <button onclick="myFunction()">Try it</button> <

如果需要找出的链接是来自外部网站 例如:如果图像链接是

然后需要显示外部图像

elseimage.jpg则需要显示内部图像

为此,我生成了如下代码

  var img= https://static.scientificamerican.com/sciam/cache/file/268F292B-5DDD-4DB1-B5ABC6541A70ECDF.jpg;
<button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

<script>
function myFunction() {

    if () {
        greeting = "External Image";
    } else {
        greeting = "Internal image";
    }
    document.getElementById("demo").innerHTML = greeting;
}
</script>
var-img=https://static.scientificamerican.com/sciam/cache/file/268F292B-5DDD-4DB1-B5ABC6541A70ECDF.jpg;
试试看

函数myFunction(){ 如果(){ 问候语=“外部图像”; }否则{ 问候语=“内部图像”; } document.getElementById(“demo”).innerHTML=问候语; }

但我不知道做这个的条件

试试这个。我假设在
/file

<script>
function myFunction() {

if ($('img').attr('src').indexOf('https://static.scientificamerican.com/sciam/cache/file/') != -1) {
    greeting = "External Image";
} else {
    greeting = "Internal image";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>

函数myFunction(){
if($('img').attr('src').indexOf('https://static.scientificamerican.com/sciam/cache/file/') != -1) {
问候语=“外部图像”;
}否则{
问候语=“内部图像”;
}
document.getElementById(“demo”).innerHTML=问候语;
}

我会通过检查图像URL是否包含应用程序的域名来处理这个问题

借用PerKristian的回答:

获取应用程序的域:

function getBaseUrl() {
    var re = new RegExp(/^.*\//);
    return re.exec(window.location.href);
}
然后检查图像URL中是否存在该域:

if (imgUrl.toLowerCase().indexOf(domain) >= 0)
将其全部放在您的样本中:

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    if (imgUrl.toLowerCase().indexOf(getBaseUrl()) >= 0) {
        greeting = "External Image";
    } else {
       greeting = "Internal image";
    }
    document.getElementById("demo").innerHTML = greeting;
}

function getBaseUrl() {
    var re = new RegExp(/^.*\//);
    return re.exec(window.location.href);
}
</script>
试试看

函数myFunction(){ if(imgUrl.toLowerCase().indexOf(getBaseUrl())>=0){ 问候语=“外部图像”; }否则{ 问候语=“内部图像”; } document.getElementById(“demo”).innerHTML=问候语; } 函数getBaseUrl(){ var re=new RegExp(/^.*\/); 返回re.exec(window.location.href); }
您没有提供imgUrl来自何处,所以我只是在那里放置了一个占位符变量,并假设您在某个点替换或分配给该变量


这种方法唯一需要注意的是,如果图像URL出于某种原因包含域名,尽管是外部的,但您会得到误报。

示例代码中没有图像…@MikeMcCaughan我已将图像添加到代码中。不,您确实没有。我想你的意思是