简体   繁体   English

HTML onClick go 到另一个 div

[英]HTML onClick go to another div

I have a button on my webpage which when onClick I want it to show another div.我的网页上有一个按钮,当 onClick 我希望它显示另一个 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.但是,当我单击该按钮时,它将 url 中的 flash 转到正确的 div,但随后它会立即重定向回主 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:当我单击按钮时,url 将变为 flash:

www.XXXXX.com/#targetDiv www.XXXXX.com/#targetDiv

Then go immediately to www.XXXXX.com/#home然后go马上到www.XXXXX.com/#home

Any ideas why it won't display the div?为什么它不显示 div 的任何想法?

Thanks谢谢

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

     <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"/>

Reusable function to go to a particular div or section with href:可重复使用 function 到 go 到特定的 div 或带有 href 的部分:

const dynamicHrefSetter = (href: string) => {
  if (typeof window !== 'undefined') window.location.href = `#${href}`;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM