本文介绍了为什么使用JavaScript:"协议"的链接是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在20世纪90年代,有一种将Javascript代码直接放入< a> href属性中的方式,如下所示:

 < a href =javascript:alert('Hello world!')>按下我!< / a> 

然后我突然停下来看到它。它们全部被诸如以下内容所取代:

 < a href =#onclick =alert('Hello world!' )>按下我!< / a> 

对于其唯一目的是触发Javascript代码并且没有真正的 href target,为什么鼓励使用 onclick 属性而不是 href 属性?

解决方案

执行上下文是不同的,为了看到这个,试试这些链接:

 < a href =javascript:alert(this.tagName)>按下我!< / a> <! -  result:undefined  - > 
< a href =#onclick =alert(this.tagName)>按下我!< / a> <! - 结果:A - >

javascript:在全局上下文中执行,而不是作为元素的方法,这通常是你想要的。在大多数情况下,您正在处理或与您所采取行动的元素有关,最好在该环境中执行。



此外,它更清晰我根本不会使用内联脚本。查看任何框架以更清晰的方式处理这些事情。在jQuery中的示例:

$ $ $ $'''。click(function(){alert(this.tagName);}) ;


In the 1990s, there was a fashion to put Javascript code directly into <a> href attributes, like this:

<a href="javascript:alert('Hello world!')">Press me!</a>

And then suddenly I stopped to see it. They were all replaced by things like:

<a href="#" onclick="alert('Hello world!')">Press me!</a>

For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?

解决方案

The execution context is different, to see this, try these links instead:

<a href="javascript:alert(this.tagName)">Press me!</a> <!-- result: undefined -->
<a href="#" onclick="alert(this.tagName)">Press me!</a> <!-- result: A -->

javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.

Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:

$('a').click(function() { alert(this.tagName); });

这篇关于为什么使用JavaScript:&quot;协议&quot;的链接是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 12:40