Javascript 内联 onclick 转到本地锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11815295/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:12:38  来源:igfitidea点击:

Javascript inline onclick goto local anchor

javascript

提问by Satch3000

I have a button as an image...

我有一个按钮作为图像...

<img src="button.png" />

I need some javascript in an onclick where when click it will navigate to a local anchor. For example:

我需要在 onclick 中使用一些 javascript,单击时它将导航到本地锚点。例如:

<img src="button.png" onclick="navigateTo #page10" />

How can I do this?

我怎样才能做到这一点?

Update: This is the code I'm using:

更新:这是我正在使用的代码:

onclick="document.location=#goToPage';return false;"

采纳答案by bingjie2680

it looks the onClickshould be:

看起来onClick应该是:

onclick="document.location+='#goToPage';return false;" 

回答by Tivie

The solution presented in the accepted answer has the important issue that it can only be used 1 time. Each consecutive click appends #goToPageto location and the window won't navigate to the anchor.

已接受的答案中提出的解决方案具有一个重要问题,即它只能使用 1 次。每次连续单击都会附加#goToPage到位置,并且窗口不会导航到锚点。

A solution is to remove the anchor part before appending a new anchor:

一种解决方案是在附加新锚之前删除锚部分:

function goToAnchor(anchor) {
  var loc = document.location.toString().split('#')[0];
  document.location = loc + '#' + anchor;
  return false;
}

Usage example:

用法示例:

<a href="#anchor" onclick="goToAnchor('anchor')">Anchor</a>

NOTE: The anchor needs to be enclosed in quotes, without the hash prefix.

注意:锚点需要用引号括起来,没有哈希前缀。

回答by Paul Fleming

Wrap it in an anchor tag. You don't need to use JS.

将其包裹在锚标签中。你不需要使用JS。

<a data-role="none" href="#page10"><img src="button.png" /></a>

回答by Ricardo Frasson

Try using with / slash for root or /folder/, so it can be used many times.

尝试将 / 斜线用于 root 或 /folder/,以便可以多次使用。

onclick="document.location='/#goToPage';return false;" 

onclick="document.location='/folder/#goToPage';return false;"