简体   繁体   English

如何使onClick和href协同工作?

[英]How do i make onClick and href work together?

I have an a element which has his own href and it works perfectly. 我有一个具有自己的href a元素,并且效果很好。 The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored: 问题是,除了href元素之外,我还想创建onClick函数,但是当我这样做时, href被忽略:

<li><a href="#someSectionOfThePage" onClick={someFunction}>GO TO SECTION</a></li>

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage . 使用此语法, someFunction可以运行,但是我没有被重定向到#someSectionOfThePage

This should do the trick: 这应该可以解决问题:

<li onClick={someFunction}>
   <a href="#someSectionOfThePage">GO TO SECTION</a>
</li>

When you click the <li> it will execute the function... and when you click the <a> it will process the href . 当您单击<li> ,它将执行功能...,而当您单击<a> ,它将处理href Since you'll be clicking this element, both will work the same time. 由于您将单击此元素,因此两者将同时工作。

The href present in the a tag is not going to work because of the onClick event. 由于onClick事件,标签中存在的href无效。 After clicking the element, instead of redirecting you to the section of the page, it executes someFunction() . 单击元素后,它执行someFunction()而不是将您重定向到页面的该部分。 You may try adding location.href = "#someSectionOfThePage" to someFunction() which will do the work of href . 您可以尝试将location.href = "#someSectionOfThePage"添加到someFunction() ,这将完成href的工作。

您也可以尝试为li添加一个click event处理程序,并确保li和anchor标签a width相同。

Although it is not advisable but if you still want to use both then this might do the trick: 虽然不建议这样做,但是如果您仍然想同​​时使用两者,则可以解决问题:

someFunction= ()=>{
  window.location.href("#someSectionOfThePage");
  //do your onClick stuff here
};

<li>
  <span onClick={this.someFunction}>GO TO SECTION</span>
</li>

Hope this helps!! 希望这可以帮助!!

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

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