将 JavaScript 代码放入 中的不同方法有什么区别?

发布于 2024-07-08 17:50:27 字数 968 浏览 6 评论 0原文

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

function DoSomething() { ... return false; }
  1. link
  2. link
  3. link
  4. link >

我理解尝试输入有效 URL 而不仅仅是 JavaScript 代码的想法,以防万一用户没有启用 JavaScript。 但出于本次讨论的目的,我需要假设 JavaScript 已启用(没有它他们无法登录)。

我个人喜欢选项 2,因为它允许您查看将要运行的内容——在调试将参数传递给函数的情况下特别有用。 我已经使用了很多次了,还没有发现浏览器问题。

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

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

相关问题:JavaScript 链接的 Href:“#”或“javascript:void( 0)”?

I have seen the following methods of putting JavaScript code in an <a> tag:

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>

I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn't have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can't login without it).

I personally like option 2 as it allows you to see what's going to be run–especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven't found browser issues.

I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn't "real". It will go absolutely no where.

Is there one that isn't support or is really bad, when you know the user has JavaScript enabled?

Related question: Href for JavaScript links: “#” or “javascript:void(0)”?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

岛徒 2024-07-15 17:50:27

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>
痴骨ら 2024-07-15 17:50:27

当您可以使用 addEventListener/attachEvent 时,为什么要这样做? 如果没有 href 等效项,请不要使用 ,而使用

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.

微凉 2024-07-15 17:50:27

您忘记了另一种方法:

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

使用 JavaScript 代码:

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

我无法评论哪个选项具有最好的支持或哪个在语义上是最好的,但我只想说我更喜欢这种风格,因为它将您的内容与您的内容分开。 JavaScript 代码。 它将所有 JavaScript 代码保存在一起,这更容易维护(特别是如果您将其应用于许多链接),您甚至可以将其放入外部文件中,然后可以打包该文件以减少文件大小并由客户端浏览器缓存。

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.

穿越时光隧道 2024-07-15 17:50:27
<a href="#" onClick="DoSomething(); return false;">link</a>

我会这样做,或者:

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

视情况而定。 对于较大的应用程序,第二个是最好的,因为它可以整合您的事件代码。

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

北座城市 2024-07-15 17:50:27

方法 #2 在 FF3 和 IE7 中存在语法错误。
我更喜欢方法 #1 和 #3,因为 #4 用“#”弄脏了 URI,尽管会减少输入次数...
显然,正如其他响应所指出的,最好的解决方案是将 html 与事件处理分开。

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.

盛装女皇 2024-07-15 17:50:27

我注意到 this:

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

和 this:

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

之间的一个区别是,如果在任何一种情况下您都有:

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

那么对于第一个示例, act2 将在 act1 之前运行,而在第二个示例中例如,情况恰恰相反。

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.

记忆消瘦 2024-07-15 17:50:27

仅限现代浏览器

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

跨浏览器

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

您可以在文档准备好之前运行此命令,单击按钮将起作用,因为我们将事件附加到文档。

来源:

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:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文