Add behavior to existing onclick attribute in javascript


how can I add more behavior to existing onclick events, for example. if an existing object looks like

<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 onclick, which would also do the following

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

Best regards, Keshav

+3
source share
5 answers

Here's the dirtiest way :)

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

Here is a slightly simpler version. Wrap everything in a function:

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

JavaScript:

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

And here is the right way to do it. Use an event logging model instead of relying on an attribute or property onclick.

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

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

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

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

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

+6

- :

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

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

0

:

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

plain ol 'JavaScript - .

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

It is worth noting that jQuery makes this a little easier. See the documentation for click , bind, and one , and, in general, the section attaching an event handler .

0
source

Source: https://habr.com/ru/post/1755090/


All Articles