简体   繁体   中英

Why my toggle visibility javascript function is not working?

I have this folder structure:

htdocs/
  - a.php
  - plugin/
      - b.php
  - website/
      - c.php
  - js/
      - common.js

I have these functions on common.js :

function togglevisibility (id)
{
    var doc = document.getElementById(id);
    if (doc.style.display == "" || doc.style.display == "block") doc.style.display = "none"; else
    if (doc.style.display == "none") doc.style.display = "block";
}

function gotourl (url)
{
    window.location = url;
}

Now, let's say I have this script on a.php :

include_once "plugin/b.php";
include_once "website/c.php";

And then, b.php :

<script type="text/javascript" src="js/common.js"></script>

And then, c.php :

<a href="#" onclick="togglevisibility('data');">show data</a><br>
<a href="#" onclick="
    var doc = document.getElementById('data');
    if (doc.style.display == '' || doc.style.display == 'block') doc.style.display = 'none'; else
    if (doc.style.display == 'none') doc.style.display = 'block';">
    display data</a>

<div id="data" style="display:none">This is the data</div>

<a href="#" onclick="gotourl('www.google.com');">goto google.com</a>

And then we run the site using http://localhost/a.php .

The problem is that gotourl function is working, but togglevisibility function (on link show data ) isn't working. And if I copy paste the function's contents into the inline javascript (like the display data link), it's working. Can you give a hint on where this went wrong? I have searching the problem for hours. Everything seems correct.

<a href="e.com">E</a>

The "href" is the URL, so you should replace 'window.location' with 'window.location.href'.

See docs: https://www.w3schools.com/js/js_window_location.asp

And for your togglevisibility(), I'm not sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM