为什么我的切换可见性javascript函数不起作用

Why my toggle visibility javascript function is not working?

本文关键字:javascript 函数 不起作用 可见性 我的 为什么      更新时间:2023-09-26

我有这样的文件夹结构:

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

我在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;
}

现在,假设我在a.php:上有这个脚本

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

然后,b.php:

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

然后,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>

然后我们使用http://localhost/a.php运行该站点。

问题是gotourl函数正在工作,但togglevisibility函数(在链接show data上(不工作。如果我将函数的内容复制粘贴到内联javascript中(如display data链接(,它就可以工作了。你能提示一下哪里出了问题吗?我已经研究这个问题好几个小时了。一切似乎都是正确的。

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

";href"是URL,因此应将"window.location"替换为"window.location.href'.">

请参阅文档:https://www.w3schools.com/js/js_window_location.asp

至于你的togglevisibility((,我不确定。