如何将JavaScript onclick事件设置为具有css的类 [英] How do you set a JavaScript onclick event to a class with css

查看:432
本文介绍了如何将JavaScript onclick事件设置为具有css的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想说的是,每当用户点击任何链接时,都会弹出一个提示hohoho的提醒。
我需要添加 onclick =alert('hohoho')到每个链接,或者我可以设置这个CSS,使其适用于每个链接?

Let's say I want that every time the user click any link an alert pops up that says "hohoho". Do I need to add onclick="alert('hohoho')" to every link or can I set this with CSS so that it works with every link?

推荐答案

你不能使用CSS,但你可以使用Javascript, =http://jquery.com> jQuery 。

You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.

如果你想在没有jQuery的情况下这样做:

If you want to do it without jQuery:

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            anchor.onclick = function() {
                alert('ho ho ho');
            }
        }
    }
</script>

而且没有jQuery,只有一个特定的类(例如: hohoho ):

And to do it without jQuery, and only on a specific class (ex: hohoho):

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            if(/\bhohoho\b/).match(anchor.className)) {
                anchor.onclick = function() {
                    alert('ho ho ho');
                }
            }
        }
    }
</script>

如果您可以使用 jQuery ,则您可以为所有锚点执行此操作:

If you are okay with using jQuery, then you can do this for all anchors:

<script>
    $(document).ready(function() {
        $('a').click(function() {
            alert('ho ho ho');
        });
    });
</script>

此jQuery代码段仅将其应用于具有特定类的锚点:

And this jQuery snippet to only apply it to anchors with a specific class:

<script>
    $(document).ready(function() {
        $('a.hohoho').click(function() {
            alert('ho ho ho');
        });
    });
</script>

这篇关于如何将JavaScript onclick事件设置为具有css的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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