开发者

Function for an event

开发者 https://www.devze.com 2023-01-22 03:17 出处:网络
I would like to create a function from this: element.onclick = function(e){ ... code ... } To something li开发者_运维问答ke this:

I would like to create a function from this:

element.onclick = function(e){
    ... code ...
}

To something li开发者_运维问答ke this:

element.onclick  = doSomething(e);
element2.onclick = doSomething(e);

function doSomething(e){
    ... code ...
}

In this way I could call the function multiple times but in this way e is not passed as an event so doesn't works.

How should I do this?


Not sure exactly what you mean, but you can declare a function and use it as the handler for multiple elements. The event argument will still be passed.

element.onclick = someHandler;
anotherElem.onclick = someHandler;
yetAnotherElem.onclick = someHandler;

function someHandler(e){
    e = e || event;
    ... code ...
}

Each of the 3 elements will call the same handler, and have the event object as its argument.


EDIT: With regard to your edit, you were calling the function and assigning its return value to onclick instead of assigning the function itself.

Seems from your comment that you figured that out though. :o)


function onClickHandler(e){
    //Do stuff...
}

element.onclick = onClickHandler;


I think you are asking how to create a normal function and use it in various ways?

function fnName(e) {
  ... code ...
}

Can be used in various ways:

element.onclick = fnName;

fnName();

//Call it however you like?


First you gotta give your function a name.

function clickEvent(e) {
    ... do stuff ...
}

Then attach it onto the element like this:

element.onClick = clickEvent;

When the event is triggered, the event will automatically get passed into the function.


You need to write it in the form of:

function fnName(e){
    ... code ...
}

and then you can call fnName and pass the variable you need.

If your function does not really need the 'e', you can write

function fnName(){
    ...code...
}


you can do this:

element.onclick = function(e){

myfunc();

}

function myfunc()

{

... code

}

0

精彩评论

暂无评论...
验证码 换一张
取 消