向 javascript 中现有的 onclick 属性添加更多行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3270600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:42:43  来源:igfitidea点击:

Add more behavior to existing onclick attribute in javascript

javascripthtmlonclick

提问by keshav84


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


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

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

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

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

我如何向 onclick 添加更多行为,这些行为也可以执行以下操作

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

Best Regards, Keshav

最好的问候, 凯沙夫

回答by Anurag

Here's the dirtiest way :)

这是最肮脏的方式:)

<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();
}

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

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

<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);

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

addEvent下面给出了该函数的跨浏览器实现(来自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");
    }
}

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.

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

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

回答by Russ Cam

Another way not mentioned is to capture the function currently assigned to the element.onclickattribute, then assign a new function that wraps the old one. A simple implementation to demonstrate would be something like

另一种没有提到的方法是捕获当前分配给element.onclick属性的函数,然后分配一个新函数来包装旧函数。一个简单的演示实现将类似于

function addEvent(element, type, fn) {
    var old = element['on' + type] || function() {};
    element['on' + type] = function () { old(); fn(); };
}

var a = document.getElementById('a');

function sayHello(){
    alert('hello');
}

function sayGoodMorning(){
    alert('Good Morning');
}

addEvent(a, 'click', sayHello);
addEvent(a, 'click', sayGoodMorning);

Working Demohere

工作演示在这里

回答by Darin Dimitrov

One way would be to write a third function:

一种方法是编写第三个函数:

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

function sayGoodMorning(){
    alert('Good Morning');
}

function foo() {
    alert("say hello again");
    sayGoodMorning();
}
</script>

回答by sushil bharwani

<a href="http://abc" onclick="sayHello(),sayX(),sayY(),sayZ()">link</a>

<a href="http://abc" onclick="sayHello(),sayX(),sayY(),sayZ()">link</a>

would also work

也能用

回答by Weston C

Assuming a slight change to your code:

假设您的代码略有变化:

<a href="http://abc" id="a1" onclick="sayHello()">link</a>

In plain ol' JavaScript, you'd do something like this.

在普通的 ol' JavaScript 中,你会做这样的事情。

var a = document.getElementById('a1');
a.onclick = function () { alert('say hello again'); a.onclick(); }

It's worth noting that jQuery makes this a bit easier. See the documentation on the click, bind, and one, for example, and in general the section on event handler attachment.

值得注意的是,jQuery 使这更容易一些。例如,请参阅有关clickbindone的文档,以及一般情况下有关事件处理程序附件的部分。