在标签中调用JavaScript函数的更好方法 [英] Better way to call javascript function in a tag

查看:79
本文介绍了在标签中调用JavaScript函数的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下哪一种方法可以更好地从标签中调用js函数?

 < a href = JavaScript的:someFunction() > LINK< / A> 

OR

 < a href =#onclick =someFunction();返回false;> LINK< / a> 

我曾见过这里的问题,但它说< span onclick =someFunction()> 是一个更好的选择,但由于某些原因我必须使用< a> links。



编辑:我正在寻找适用于Android和iPad的跨浏览器和跨平台解决方案

解决方案

两者都不错。

与实际的标记无关,例如,在jQuery中,你可能会做类似于

  $('#the-element')。点击(函数(){/ *在这里执行动作* /}); 

c $ c $< script> block。



这个优点是它


  1. 分隔mar kup和行为,就像CSS分隔标记和样式一样
  2. 集中配置(这是1的必然结果)。
  3. 可以扩展的使用jQuery强大的选择器语法来包含多个参数。

此外,它会优雅地降级(但如果使用 onclick event),因为如果用户没有启用JavaScript,您可以为链接标签提供 href



当然,如果您不使用jQuery或其他JavaScript库(但是为什么要这样做),那么这些参数仍然会计数。


Which of the following ways is a better way to call a js function from an a tag?

<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.

EDIT: I am looking for a cross browser & cross platform solution which should work on androids & iPads too.

解决方案

Neither is good.

Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like

$('#the-element').click(function () { /* perform action here */ });

in a separate <script> block.

The advantage of this is that it

  1. Separates markup and behaviour in the same way that CSS separates markup and style
  2. Centralises configuration (this is somewhat a corollary of 1).
  3. Is trivially extensible to include more than one argument using jQuery’s powerful selector syntax

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.

Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).

这篇关于在标签中调用JavaScript函数的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆