开发者

Javascript Hide Element by ID Based on Browser

开发者 https://www.devze.com 2023-02-04 12:06 出处:网络
I am trying to show a message to all browsers and remove it though javascript if it is supported. Currently the only way it will be hidden is if I click a hide button. It won\'t run in my if statement

I am trying to show a message to all browsers and remove it though javascript if it is supported. Currently the only way it will be hidden is if I click a hide button. It won't run in my if statement.

<html>
<head>

<script type="text/javascript">
var browser=navigator.appCodeName + navigator.appName;
function hideStuff(id) {
  document.getElementById(id).style.display = 'none';
 }

function supportedBrowser() {
if (browser == "MozillaNetscape")
  {
  document.write("Browser is Mozilla Netscape");
  }
else if (browser == "MozillaOpera")
  {
  document.write("Browser is Mozilla Opera");
  hideStuff('browserMessage');
  }
else
  {
alert("Please upgrade your browser.");
 }
}
//-->
</script>
</head>
<body>
<a href="#" onclick="hideStuff('browserMessage'); return false;">Hide</a>
<br><br>
<p id="browserMessage" style="display: inline;">Please use a supported browser.</p>
</body>
</html>

Changed as according to "bluevoodoo1"

<html>
<head>

<script type="text/javascript">
var browser=navigator.appCodeName + navigator.appName;
function hideStuff(id) {
        document.getElementById(id).style.display = 'none';
    }
function supportedBrowser() {
if (browser == "MozillaNetscape")
  {
  document.write("Browser is Mozilla Netscape");
  }
else if (browser == "MozillaOpera")
  {
  document.write("Browser is Mozilla Opera");
  //hideStuff('browserMessage');
  }
else
  {
alert("Please upgrade your browser.");
    }
}
function init() {
         supportedBrowser();
       //etc
    }
    window.onload = supportedBrowser;
    /开发者_StackOverflow社区/-->
</script>
</head>
<body>
<a href="#" onclick="hideStuff('browserMessage'); return false;">Hide</a>
<br><br>
<p id="browserMessage" style="display: inline;">Please use a supported browser.</p>
<p>This text shoudld not be hidden.</p>
</body>
</html>

Does anyone know what I am doing wrong?


you might need use the window.onload handler... (jquery's "document.ready" is probably preferred, but I'm using some native javascript below)

<script>
    function init() {
         supportedBrowser();
         //etc
    }
    window.onload = init; 
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消