向 javascript 中的现有 onclick 属性添加更多行为 [英] Add more behavior to existing onclick attribute in javascript

查看:34
本文介绍了向 javascript 中的现有 onclick 属性添加更多行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


如何向现有的 onclick 事件添加更多行为,例如如果现有对象看起来像


how can i add more behaviour to existing onclick events e.g. if the existing object looks like

<a href="http://abc" onclick="sayHello()">link</a>
<script>
function sayHello(){
    alert('hello');
}

function sayGoodMorning(){
    alert('Good Morning');
}
</script>

我怎样才能在 onclick 中添加更多行为来执行以下操作

how can i add more behavior to the onclick that would do also the following

alert("say hello again");
sayGoodMorning()

最好的问候,凯沙夫

推荐答案

这是最肮脏的方式:)

<a href=".." onclick='sayHello();alert("say hello again");sayGoodMorning()'>.</a>

这是一个稍微理智的版本.将所有内容包装成一个函数:

Here's a somewhat saner version. Wrap everything into a function:

<a href=".." onclick="sayItAll()">..</a>

JavaScript:

JavaScript:

function sayItAll() {
    sayHello();
    alert("say hello again");
    sayGoodMorning();
}

这是正确的方法.使用事件注册模型,而不是依赖 onclick 属性或属性.

And here's the proper way to do it. Use the event registration model instead of relying on the onclick attribute or property.

<a id="linkId" href="...">some link</a>

JavaScript:

JavaScript:

var link = document.getElementById("linkId");
addEvent(link, "click", sayHello);
addEvent(link, "click", function() {
    alert("say hello again");
});
addEvent(link, "click", sayGoodMorning);

addEvent 函数的跨浏览器实现如下(来自 scottandrew.com):

A cross-browser implementation of the addEvent function is given below (from scottandrew.com):

function addEvent(obj, evType, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, false);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        alert("Handler could not be attached");
    }
}

请注意,如果所有 3 个操作都必须按顺序运行,那么您仍应继续将它们包装在一个函数中.但是这种方法仍然优于第二种方法,虽然它看起来有点冗长.

Note that if all 3 actions must be run sequentially, then you should still go ahead and wrap them in a single function. But this approach still tops the second approach, although it seems a little verbose.

var link = document.getElementById("linkId");
addEvent(link, "click", function() {
    sayHello();
    alert("say hello again");
    sayGoodMorning();
});

这篇关于向 javascript 中的现有 onclick 属性添加更多行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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