javascript - 外部链接无法正常工作 html/javascript

标签 javascript html hyperlink

我在我的客户网站上创建了一个点击显示选项。那里工作得很好。 其各自的代码如下。

<style>
a{padding:0;margin:0;color:#009cbb;font-weight:bold;text-decoration:none;}
</style>
<p>
<div><a href="#welcome" onclick="toggle_visibility('welcome');">Welcome</a></div>
<div id="welcome" style="display:none;">This is test</div>

<div><a href="#focus" onclick="toggle_visibility('focus');">Focus</a></div>
<div id="focus" style="display:none;">This is test2
</div>

<div><a href="#cataracts" onclick="toggle_visibility('cataracts');">Cataracts</a></div>
<div id="cataracts" style="display:none;">This is test2
</div>
</p>
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>

当我从外部页面链接 test1 时,它应该显示 test1 并保持关闭其他 2 个页面,但问题是当我单击该链接时,它会显示所有这些都已关闭。

链接代码是

<a href="http://website.com/page.php#welcome" style="color:#009bd9;text-decoration:none;">Read More ></a>

请帮助我,当有人点击“阅读更多”时,它会将欢迎消息显示为打开,而其他人则显示为关闭。

谢谢

最佳答案

试试这个 - 在 Windows 上的 IE8、Chrome32 和 Fx 24 中进行了测试

Live Demo Live Demo With Hash

function toggle_visibility(link) {
  var id = link.hash.substring(1);
  var obj = document.getElementById(id);
  if (obj) obj.style.display = obj.style.display == "block"?"none":"block";
  return false;
}
window.onload=function() {
  var id = location.hash?location.hash.substring(1):"";
  if (id)  document.getElementById(id).style.display="block";
}

在每个链接上使用这种格式(也应该重构为不引人注目)

onclick="return toggle_visibility(this);"

请注意(这个)

关于javascript - 外部链接无法正常工作 html/javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155823/

相关文章:

javascript - 在外部网站的页面加载上自动执行javascript功能

ruby-on-rails - 我可以使用link_to生成一个内部为span的链接吗?

javascript - JQuery 和 Fancybox 单击图像打开新页面/链接(更新现有代码)

javascript - angular for each 如何为每个子对象添加属性

javascript - jquery next() 不工作?

javascript - 为什么 Jest 不会运行? "TypeError: environment.setup is not a function"

html - 建立一个主要的链接栏

javascript - 在元素上绘制边框,但不捕获事件

html - 如何在 bootstrap 3 css 中生成以下布局

html - 内联 div 不在服务器上另一个 div/部分的中心,但在本地主机上很好