如果src是http://,则隐藏iframe

Hide iframe if src is http:// without link

本文关键字:隐藏 iframe src http 如果      更新时间:2023-09-26

我需要隐藏iframe,如果

src is "http://". 

我想做的:

<script type="text/javascript"> 
    if ( $('iframe[src][src="http://"]') )
        document.getElementById('iframe').style.display='none';
    else
        document.getElementById('iframe').style.display='block';
</script>
html

<iframe id="iframe" src="url" ></iframe>

你必须改变你的jQuery选择器为iframe[src="http://"]或一个更好的解决方案是使用CSS隐藏你的iframe

当你在处理与样式相关的事情时,你应该总是使用CSS而不是javascript。

iframe[src="http://"] {
  display: none;  
}
<iframe src="http://"></iframe>
<iframe src=""></iframe>

如果你想隐藏只有src="http://"的iframe,你可以用jQuery和一些正则表达式。

注意:在Chrome中,"http://"的src被报告为"http:"。在iOS的Safari和Chrome中,它被报告为"http:/"。为了解释这种差异,可以使用一个简单的正则表达式。

$('iframe').each(function() {
  var src = this.src.toLowerCase();
  if (/^http:['/]{0,2}$/i.test(src)) {
    $(this).hide();
  } else {
    $(this).show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
1. http://<br><iframe id="iframe" src="http://"></iframe><br>
2. http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png<br><iframe id="iframe" src="http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png"></iframe><br>


如果您还想隐藏src=""或没有src设置的iframe,或者src="https://",您可以使用下面的代码。条件src === self.location.href测试src=""。正则表达式/^https?:['/]{0,2}'w/i测试"http(s)://"加一个单词字符。如果没有找到,则隐藏iframe。非http(s) src的iframe也被隐藏。

$('iframe').each(function() {
  var src = this.src.toLowerCase();
  if (src === self.location.href || !/^https?:['/]{0,2}'w/i.test(src)) {
    $(this).hide();
  } else {
    $(this).show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
1. http://<br><iframe id="iframe" src="http://"></iframe><br>
2. https://<br><iframe id="iframe" src="https://"></iframe><br>
3. http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png<br><iframe id="iframe" src="http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png"></iframe><br>
4. ""<br><iframe id="iframe" src=""></iframe><br>
5. (blank)<br><iframe id="iframe"></iframe><br>
6. "a.htm"<br><iframe id="iframe" src="a.htm"></iframe><br>
7. src<br><iframe id="iframe" src></iframe><br>

试试这个:

<script>
    function checkFrame(){
        if($('iframe[src][src="http://"]'))
            document.getElementById('iframe').style.display='none';
        else
            document.getElementById('iframe').style.display='block';
    }
</script>

并在需要检查时调用该函数。也许是body标签上的onLoad参数?

但是我必须问,为什么"else"显示它,它在默认情况下会显示。

另外,如果值为空怎么办?

好吧,希望这有帮助!

您可以将onload处理程序附加到iframe:

var iframe = document.getElementById('iframe');
iframe.onload = function() {
    if(iframe.src == 'http://') {
        iframe.style.display = 'none'; 
    } else {
        iframe.style.display = '';//default
    }
}