简体   繁体   中英

Manually triggering a function click event object

I've got the following code:

function myfunc(e){
    console.log(e.target);
}

which returns the event of the clicked target. But I want to trigger that same function without clicking on a target.

Is this possible? is it possible to do something like this?

myfunc(document.getElementById('btn').target);

I think you should modify your function like this, to use with and without event trigger (if you only need the element object)

function myfunc(e){
    var ele = e ? e.target : document.getElementById('btn');
    console.log(ele);
}

Triggering a .click() with javascript manually will directly bind the click to that element so in your case an event will not be passed by doing this . Also , target is a property of the event object so calling it directly on getElementById will not work . Logically once you getElementById then you already have your target because id's are unique .

On the other hand jquery library allows you to trigger clicks and pass custom data like so :

Example :

$( "button" ).on( "click", {name: "John"}, sayName);

function sayName(event){

    alert(event.data.name )

}

Hope this helps .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM