我一直在尝试使用这个 http://www.gloucesterwebdesign.com/showhidecontent/
但我不想点击链接,而是希望一些 JavaScript 调用此函数
喜欢
if(input == true){
toggleLayer('id');
}
else if(input == false){
toggleLayer('id2');
}
脚本调用了toogleLayer函数,但是没有任何反应,诅咒 输入值放置在页面加载时运行的其他脚本中。我一直在想这是否是问题所在。有人想对此发表评论吗?
-- 更新-- 所以我被要求提供更多的代码, http://pastebin.com/UD3tjz1s
- localStorage 中的值是在其他页面上设置的,因此之后您只能获取此页面。这只是为了显示我使用的是哪种数据
我有点 javaScript 菜鸟,所以希望它不会很难阅读
最佳答案
好的,我做了一个快速测试,这就可以了。只需用它替换您当前的功能,它就会更干净、更简单。此外,document.getElementById(id) 在当前的每个浏览器中都受支持,并且可以追溯到 IE6,因此除非您想要 netscape 支持,否则您不需要;需要您的资源提供的所有额外代码。
function toggleLayer(id){
// get the element (this is supported in all modern browsers)
var element = document.getElementById(id);
// set the style display of this element to none if its set to be
// anything else than none, otherwise set it to block
element.style.display = element.style.display != "none"
? "none"
: "block";
}
我测试了这个并且它有效。
编辑 - [不同的东西!]
好的,对不起,我有点误解了,但我找到了解决它的方法。归结为:因为您的 javascript 代码在您的 DIV 元素之上,所以它会在页面创建 DIV 元素之前执行。所以 javascript 会寻找元素,它会返回 undefined 因为,嗯,它们还没有定义。所以你必须将你的脚本移动到结束标记之前,或者将以下内容添加到代码中(请不要我还添加了一个间隔来查看你的函数工作):
window.onload = function(){
setInterval(setSize,1000);
// the rest of your functions here - the above interval is so you can see it toggling
}
// function toggleLater(){...} here
您可能还想将 ToggleLayer 移到 window.onload 函数的外部,因为否则您无法从页面触发它(同样,该函数现在定义在 window.onload 内部并且在 DIV 元素的范围之外。 ..).
关于javascript - 试图在 javascript 调用中隐藏带有内容的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25239934/