将 JavaScript 代码放入 < a > 的不同方法之间有什么区别?

我见过以下将 JavaScript 代码放入 <a>标记的方法:

function DoSomething() { ... return false; }
  1. <a href="javascript:;" onClick="return DoSomething();">link</a>
  2. <a href="javascript:DoSomething();">link</a>
  3. <a href="javascript:void(0);" onClick="return DoSomething();">link</a>
  4. <a href="#" onClick="return DoSomething();">link</a>

我理解尝试放置一个有效的 URL 而不仅仅是 JavaScript 代码的想法,以防用户没有启用 JavaScript。但是出于本文讨论的目的,我需要假设启用了 JavaScript (没有它他们就不能登录)。

我个人喜欢选项2,因为它允许您查看将要运行的内容,在调试将参数传递给函数的地方时尤其有用。我用过很多次,没有发现浏览器问题。

我曾经读到人们推荐4,因为它给用户一个真实的链接,但实际上,# 不是“真实的”。它绝对不会去任何地方。

当您知道用户启用了 JavaScript 时,是否存在不支持或者非常糟糕的情况?

相关问题: Href = “ https://stackoverflow. com/questions/134845/Href-for-JavaScript-links-or-javascriptvoid0”> Href for JavaScript links: “ #”or“ JavaScript: void (0)”

53825 次浏览

Why would you do this when you can use addEventListener/attachEvent? If there is no href-equivalent, don't use an <a>, use a <button> and style it accordingly.

You forgot another method:

5: <a href="#" id="myLink">Link</a>

With the JavaScript code:

document.getElementById('myLink').onclick = function() {
// Do stuff.
};

I can't comment on which of the options has the best support or which is semantically the best, but I'll just say that I much prefer this style because it separates your content from your JavaScript code. It keeps all the JavaScript code together, which is much easier to maintain (especially if you are applying this to many links), and you can even put it in an external file which can then be packed to reduce filesize and cached by client browsers.

<a href="#" onClick="DoSomething(); return false;">link</a>

I will do this, or:

<a href="#" id = "Link">link</a>
(document.getElementById("Link")).onclick = function() {
DoSomething();
return false;
};

Depending on the situation. For larger apps, the second one is best because then it consolidates your event code.

I quite enjoy Matt Kruse's Javascript Best Practices article. In it, he states that using the href section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, there's no reason you can't have a simple HTML page that all your JavaScript links can point to for their href section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to "best practices" and accomplish your goal:

<a href="javascript_required.html" onclick="doSomething(); return false;">go</a>

Method #2 has a syntax error in FF3 and IE7. I prefer methods #1 and #3, because #4 dirty the URI with '#' although causes less typing... Obviously, as noted by other responses, the best solution is separate html from event handling.

One difference I've noticed between this:

<a class="actor" href="javascript:act1()">Click me</a>

and this:

<a class="actor" onclick="act1();">Click me</a>

is that if in either case you have:

<script>$('.actor').click(act2);</script>

then for the first example, act2 will run before act1 and in the second example, it will be the other way around.

Modern browsers only

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);


function doSomething(event){
console.log(this); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>


<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me">Button 1</button>
<input class="click-me" type="button" value="Button 2">


</body>
</html>

Cross-browser

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}


cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);


function doSomething(event){
console.log(this); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>


<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me">Button 1</button>
<input class="click-me" type="button" value="Button 2">


</body>
</html>

You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

Sources: