使用JavaScript显示/隐藏div,而无需刷新页面 [英] Show/Hide div using javascript without page refresh
问题描述
我有一个脚本,可在页面上显示/隐藏多个独立的div.问题是,当您单击以显示一个div时,无论页面上的什么位置,它都会自动集中在第一个div上.有没有办法专注于显示的div?
I have a script that shows /hides multiple independent divs on a page. The problem is that when you click to show a div, no matter where on the page, it will automatically focus on the first div. Is there a way to focus on the div that was displayed?
这是javascript:
here is the javascript:
function toggleOptions(e) {
var ele = e;
var text = e.parentElement.querySelector('.toggleOptions')
if(text.style.display == "none") {
//ele.style.display = "none";
text.style.display = "block";
text.innerHTML = "TESTING";
ele.innerHTML = "hide";
}
else {
text.style.display = "none";
//text.innerHTML = "Hide GPS";
ele.innerHTML = "show";
}
return false;
}
这是html:
<div>
<a href="#" onclick="toggleOptions(this);" style="display:block;">
show
</a>
<div class="toggleOptions" style="display: none">
ITEM 1 OPTIONS
</div>
</div>
<div>
<a href="#" onclick="toggleOptions(this);" style="display:block;">
show
</a>
<div class="toggleOptions" style="display: none">
ITEM 2 OPTIONS
</div>
</div>
<div>
<a href="#" onclick="toggleOptions(this);" style="display:block;">
show
</a>
<div class="toggleOptions" style="display: none">
ITEM 3 OPTIONS
</div>
</div>
这是工作的缩影 http://jsfiddle.net/YE6XZ/1/
推荐答案
让您的节目链接一个类,例如:
Give your show links a class, like:
<a class="show" href="#" onclick="toggleOptions(this);" style="display:block;">show</a>
然后将其添加到您的jQuery中:
Then add this to your jQuery:
$('a.show').click(function(e){
e.preventDefault();
});
书签锚(href="#"
)的默认操作是跳到页面顶部.这样可以防止这种情况. jsFiddle示例
The default action for a bookmark anchor (href="#"
) is to jump to the top of the page. This would prevent that. jsFiddle example
另一种无jQuery的方法是将onclicks更改为:
An alternative, jQuery-less method would be to change your onclicks to:
onclick="return toggleOptions(this);"
由于您已经返回false. jsFiddle示例
As you are already returning false. jsFiddle example
这篇关于使用JavaScript显示/隐藏div,而无需刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!