在标签中调用 javascript 函数的更好方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10877485/
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
Better way to call javascript function in a tag
提问by gopi1410
Which of the following ways is a better way to call a js function from an a tag?
以下哪种方式是从 a 标签调用 js 函数的更好方法?
<a href="javascript:someFunction()">LINK</a>
OR
或者
<a href="#" onclick="someFunction();" return false;">LINK</a>
I have seen this question here, but it says <span onclick="someFunction()">
is a better option. But due to some reasons I have to use <a>
links.
我在这里看到了这个问题,但它说<span onclick="someFunction()">
是一个更好的选择。但由于某些原因,我必须使用<a>
链接。
EDIT:I am looking for a cross browser & cross platform solution which should work on androids & iPads too.
编辑:我正在寻找一个跨浏览器和跨平台的解决方案,它也应该适用于安卓和 iPad。
采纳答案by Konrad Rudolph
Neither is good.
两者都不好。
Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like
行为应该独立于实际标记进行配置。例如,在 jQuery 中,您可能会执行类似的操作
$('#the-element').click(function () { /* perform action here */ });
in a separate <script>
block.
在一个单独的<script>
块中。
The advantage of this is that it
这样做的好处是
- Separates markup and behaviour in the same way that CSS separates markup and style
- Centralises configuration (this is somewhat a corollary of 1).
- Is trivially extensible to include more than one argument using jQuery's powerful selector syntax
- 以与 CSS 分离标记和样式相同的方式分离标记和行为
- 集中配置(这在某种程度上是 1 的推论)。
- 使用 jQuery 强大的选择器语法可以轻松扩展以包含多个参数
Furthermore, it degrades gracefully (but so would using the onclick
event) since you can provide the link tags with a href
in case the user doesn't have JavaScript enabled.
此外,它会优雅地降级(但使用onclick
事件也会降级),因为您可以为链接标签提供href
,以防用户没有启用 JavaScript。
Of course, these arguments stillcount if you're not using jQuery or another JavaScript library (but why do that?).
当然,如果您不使用 jQuery 或其他 JavaScript 库,这些参数仍然有效(但为什么要这样做?)。
回答by Ja?ck
Some advantages to the second option:
第二种选择的一些优点:
You can use
this
insideonclick
to reference the anchor itself (doing the same in option 1 will give youwindow
instead).You can set the
href
to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to useonclick="return someFunction();"
andreturn false
from inside the function oronclick="return someFunction(); return false;"
to prevent default action).I've seen weird stuff happen when using
href="javascript:someFunction()"
and the function returns a value; the whole page would get replaced by just that value.
您可以使用
this
insideonclick
来引用锚点本身(在选项 1 中做同样的事情会给你window
)。您可以将 设置
href
为非 JS 兼容的 URL 以支持旧浏览器(或禁用 JS 的浏览器);支持 JavaScript 的浏览器将改为执行该函数(为了留在您必须使用的页面上onclick="return someFunction();"
并return false
从函数内部或onclick="return someFunction(); return false;"
防止默认操作)。我在使用时看到过奇怪的事情发生
href="javascript:someFunction()"
并且函数返回一个值;整个页面将被该值替换。
Pitfalls
陷阱
Inline code:
内联代码:
Runs in
document
scope as opposed to code defined inside<script>
tags which runs inwindow
scope; therefore, symbols may be resolved based on an element'sname
orid
attribute, causing the unintended effect of attempting to treat an element as a function.Is harder to reuse; delicate copy-paste is required to move it from one project to another.
Adds weight to your pages, whereas external code files can be cached by the browser.
在
document
范围内运行,而不是在范围内<script>
运行的标签内定义的代码window
;因此,符号可能会根据元素name
或id
属性进行解析,从而导致试图将元素视为函数的意外效果。更难重用;需要精细的复制粘贴才能将其从一个项目移动到另一个项目。
增加页面的权重,而浏览器可以缓存外部代码文件。
回答by Denis
I'm tempted to say that both are bad practices.
我很想说这两种做法都是不好的做法。
The use of onclick
or javascript:
should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.
应该放弃使用onclick
orjavascript:
以支持从外部脚本侦听事件,从而更好地分离标记和逻辑,从而减少重复代码。
Note also that external scripts get cached by the browser.
另请注意,浏览器会缓存外部脚本。
Have a look at this answer.
看看这个答案。
Some good ways of implementing cross-browser event listeners here.
在这里实现跨浏览器事件侦听器的一些好方法。
回答by Keith
Modern browsers support a Content Security Policyor CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
现代浏览器支持内容安全策略或 CSP。这是最高级别的 Web 安全性,如果您可以应用它,强烈建议您使用它,因为它可以完全阻止所有XSS 攻击。
Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.
您的两个建议在启用 CSP 时都会中断,因为它们允许内联 Javascript(可能由黑客注入)在您的页面中执行。
The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.
最佳做法是在 Javascript 中订阅事件,如 Konrad Rudolph 的回答。