Javascript HTML onClick 转到另一个 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10657908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML onClick go to another div
提问by ewein
I have a button on my webpage which when onClick I want it to show another div. However when I click the button it will flash in the url that it went to the correct div but then it will immediately redirect back to the main div, #home.
我的网页上有一个按钮,当 onClick 时,我希望它显示另一个 div。但是,当我单击该按钮时,它会在它转到正确 div 的 url 中闪烁,但随后它会立即重定向回主 div #home。
Code for button:
按钮代码:
<input type="button" class="flip" value="Redirect To Div" onClick="window.location='#targetDiv'" />
When I click the the button the url will flash:
当我单击按钮时,网址将闪烁:
www.XXXXX.com/#targetDiv
www.XXXXX.com/#targetDiv
Then go immediately to www.XXXXX.com/#home
然后立即访问 www.XXXXX.com/#home
Any ideas why it won't display the div?
任何想法为什么它不会显示 div?
Thanks
谢谢
回答by Rob Sedgwick
looks like your form has
看起来你的表格有
action=""
or
或者
action="#home"
instead of onclick call a function
而不是 onclick 调用函数
onclick="mylinkfunction()"
...
...
<script type-"text/javascript">
function mylinkfunction(e) {
window.location.href="#targetDiv";
/* need to stop the form sending of the form
UPDATE as comment: This may not be exactly correct syntax
for stopping a form , look up preventing form submission */
e.preventDefault();
e.stopPropagation();
}
</script>
or if your form is irrelevent set it's action and remove the javascript allogether
或者如果您的表单无关紧要,请设置它的操作并删除 javascript allogether
<form action="#targetDiv" method="get">
<input type="submit" value="go"/>
</form>
but then all you would need is actually this ..
但那么你所需要的实际上就是这个..
<a href="#targetDiv">click me</a>
if by "go to another div" you mean jump and scroll the page to a new location it is actually an anchor you need to go to
如果“转到另一个 div”是指跳转并将页面滚动到新位置,则它实际上是您需要转到的锚点
<a name="targetDiv"/>