-1

html

<p id="tag_p"><p>

javascript

function a() {
    return 1;
}


document.getElementById('tag_p').addEventListener('click', a);

I want to get return value,

Like let n = a();, when click tag p.

TTT
  • 53
  • 7
  • 2
    Your event listener should do whatever work is needed, including saving any program "state". – crashmstr Mar 11 '20 at 14:24
  • You are trying to put the "returned value" inside the `

    ` tag>

    – Jeremy Harris Mar 11 '20 at 14:24
  • This doesn't really make sense. Where is `let n`? You haven't said, but it doesn't seem to be anywhere near anything that triggers when the event occurs. – Quentin Mar 11 '20 at 14:26
  • @Quentin We should probably update that question (and provide an answer) that explicitly covers event handling. I suspect many people won't make the conceptual leap. (And maybe roll up some answers to avoid the mega-scroll.) – Dave Newton Mar 11 '20 at 14:28
  • get return value and store it in variable? I don't know if it's possible to do this. – TTT Mar 11 '20 at 14:29
  • maybe call a function, and it will caculate and then return the result – TTT Mar 11 '20 at 14:32
  • @TyT You're *already* calling a function and trying to return a value. The event handler needs to do whatever work is necessary; events are asynchronous. Event handler returns values indicate only whether or not the event was handled. – Dave Newton Mar 11 '20 at 14:35
  • @DaveNewton Thank you, I am new to javascript. I am not fully understand. But I still get something more. – TTT Mar 11 '20 at 14:53

1 Answers1

-1

You can process the result inside the EventHandler.

document.querySelector('#tag_p').addEventListener('click', function(evt){ console.log( "you clicked, I got: %d",  a() );

This takes the result from the function "a" and outputs it as a number "%d" onto the browser console. More elaborately

    document.getElementById('tag_p').addEventListener('click', function(evt){ 
        let b = a();
        b++;
        b--;
console.log( "The value of A is (after +1 and -1): %d",  b );
    }
flowtron
  • 854
  • 7
  • 20