最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - extend onclick function - Stack Overflow

matteradmin8PV0评论

I have a onclick function like this

onclick = function(){alert('hello')}

I want to add an additional function to it base on the server response so that I can display more, like not only display hello but also 'you are wele', how to writ this without jquery?

onclick = function(){alert('you are wele')}

thank you for helping.

I have a onclick function like this

onclick = function(){alert('hello')}

I want to add an additional function to it base on the server response so that I can display more, like not only display hello but also 'you are wele', how to writ this without jquery?

onclick = function(){alert('you are wele')}

thank you for helping.

Share Improve this question asked Jun 27, 2012 at 3:59 pandapanda 1,3443 gold badges14 silver badges35 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Use addEventListener.

elementSelected.addEventListener("click", function(){
    alert('you are wele');
});

This is a modern way to do that.

For that old IE, you have to do this instead:

elementSelected.attachEvent("onclick", function(){
    alert('you are wele');
});

So a more convenience way to do that is

function addEvent(ele, type, func){
    if(ele.addEventListener){
        ele.addEventListener(type, func, false);
    }else if(ele.attachEvent){
        ele.attachEvent("on" + type, func);
    }
}

addEvent(document.body, "click", function(){
    alert("Hello world!");
});

Using event listner's might do the trick ,but please note that the W3C model does not state which event handler is fired first.

I would better suggest you to check for the server response from within your function and call the second function from there.

Without jQuery, add event listeners instead of using the onClick values. Here's a description.

yourelement.attachEvent('onclick',hello);

Function hello(){
// do wat you want here
}
Post a comment

comment list (0)

  1. No comments so far