我可以使用<button>代替<a> to go to #location?

时间:2016-06-01 11:52:18

标签: javascript jquery html html5 href

I have this code.

<li class="active">
    <a href="#tab-weekly" data-toggle="tab">Weekly Payment</a>
</li>
<li>
    <a href="#tab-advance" data-toggle="tab">Advance Payment</a>
</li>
<li>
    <a href="#tab-data" data-toggle="tab">Expenses</a>
</li>

My question is that can I use <button> instead of <a> to achieve this? I changed it to buttons but they are not working.

6 个答案:

答案 0 :(得分:6)

是。使用<button type="button" onclick="window.location.href='YOUR URL HERE'">Link Text</button>

答案 1 :(得分:5)

您无法在href中使用button,但可以使用data-href属性来完成此项工作。点击button后获取data-href的值并使用window.location.hash转到定位id

$("button").click(function(){
    window.location.hash = $(this).data("href");
});
#first, #second, #third {
    height: 200px;
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button data-href="#first">First</button>
<button data-href="#second">Second</button>
<button data-href="#third">Third</button>

<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>

答案 2 :(得分:3)

您可以尝试查看this

或者您可以在其中创建button <a href>。我不知道你想把它改成按钮吗?

<button type="button">
   <a href="www.google.com">hello</a>
</button>

如果是针对该样式,您可以将样式应用于a标记,如<a href="http://google.com" class="My class">Go to Google</a>

古德勒克!

答案 3 :(得分:3)

每当你在锚标记的href属性中使用#something时,它实际上会将你带到同一页面中的id为'something'的元素。您也可以像这样使用它:

<a href="http://www.somewhere.com/anotherpage.aspx#something">click</a>

在这种情况下,它将带你到另一个页面的另一个页面的元素谁是'某事'。 现在按钮的目的是完全不同的,但有一些方法可以满足您的要求,但不建议这样做。在这种情况下你应该使用锚标记。

这是一个很棒的链接,用于显示锚点和按钮标记之间的区别。 Check it.

感谢。

答案 4 :(得分:2)

按钮没有href功能,所以除非你使用一些JS函数来模拟这个 - 不,你不能

答案 5 :(得分:2)

您可以使用<a class="your-btn-style">上的样式将按钮显示为按钮。

如果您使用的是bootstrap,只需在锚点中添加class =“btn btn-primary”即可:

<a href="#tab-advance" class="btn btn-primary" data-toggle="tab">Advance Payment</a>

我也在我的项目中使用了这种方法:

enter image description here