javascript功能_用于激活JavaScript功能的链接

javascript功能

When you are creating an app using plain JavaScript, sometimes you’ll have the necessity of triggering a function when the user clicks a link.

使用纯JavaScript创建应用时,有时您需要在用户单击链接时触发功能。

You can commonly do this in 2 ways.

通常,您可以通过2种方式执行此操作。

Suppose the function you want to execute is called handleClick():

假设您要执行的函数称为handleClick()

function handleClick() {
  alert('clicked')
}

The first way is to use a link like this:

第一种方法是使用这样的链接:

<a href="#" onclick="handleClick()">Click here</a>

The second way is to use

第二种方法是使用

<a href="javascript:void(0)" onclick="handleClick()">Click here</a>

They are both very similar syntaxes, the only difference is the href attribute value.

它们都是非常相似的语法,唯一的区别是href属性值。

The first is href="#", the second is href="javascript:void(0)". You might also see this syntax href="javascript:;", which is equivalent to the second.

第一个是href="#" ,第二个是href="javascript:void(0)" 。 您可能还会看到此语法href="javascript:;" ,相当于第二个。

Now, what is the difference in the behavior of those 2 methods?

现在,这两种方法的行为有何不同?

When the user clicks the href="#" link, you must make sure that you return false from the event handler, the otherwise the browser scrolls back to the top of the page:

当用户单击href="#"链接时, 必须确保从事件处理程序返回false ,否则浏览器将滚动回到页面顶部:

function handleClick() {
  alert('clicked')
  return false
}

Also, even if you add this but JavaScript is disabled or does not execute for some reason, the browser scrolls back to the top of the page. This is almost always a thing to avoid, so I would personally use the second form, href="javascript:void(0)".

另外,即使您添加了此功能,但由于某些原因JavaScript被禁用或无法执行,浏览器也会滚动回到页面顶部。 这几乎总是要避免的事情,因此我将亲自使用第二种形式href="javascript:void(0)"

In both ways the handleClick() function would not be called if JavaScript is disabled, or there is an error in the JavaScript and so JavaScript execution is halted.

在两种情况下,如果禁用了JavaScript或JavaScript中存在错误,则将不会调用handleClick()函数,因此将停止执行JavaScript。

To prevent this, you can use a real URL in the href as a fallback, so browsers will move the user to a specific page, using the GET HTTP method, although this is not always possible or convenient.

为避免这种情况,您可以在href使用真实的URL作为备用,因此浏览器将使用GET HTTP方法将用户移至特定页面,尽管这并不总是可能或方便的。

But it’s a best practice and best practices are not always convenient, but you have to factor them in during the design phase of your application, because you can’t just build for the ideal use case and ignore all the possible things that could go wrong.

但这是一种最佳实践,最佳实践并不总是很方便,但是您必须在应用程序的设计阶段将它们纳入考虑范围,因为您不能只是针对理想的用例进行构建,而忽略所有可能出错的事情。

If something goes wrong, the user will blame you and your broken links 🙂

如果出了问题,用户会责怪您,您的链接断开links

翻译自: https://flaviocopes.com/links-for-javascript/

javascript功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值