简体   繁体   中英

Javascript pass parameter to function

i try to pass paramater to function. When i click the div it will alert the paramater that i pass

i have 2 file

  • index.html
  • script.js

here's what i try

Example 1

index.html

<div id="thediv" >

script.js

window.onload = initialize;

    //bind event listener
        function initialize(){
             document.getElementById("thediv").onclick = myFunction(" something ");
        }
    //end of bind

    //function
        function myFunction(parameter) { alert( parameter ) };
    //end of all function
  • the trouble is the function its executed without click

Example 2

index.html

<div id="thediv" onclick="myfunction('something')" >

script.js

function myFunction(parameter) { alert( parameter ) };
  • yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
  • i want to separate my code into 3 section (similiar with example1)
    • the view(html element)
    • the element have which listener
    • the function

what should i do? or can i do this? (i don't want to use another library)

Placing () (with any number of arguments in it) will call a function. The return value ( undefined in this case) will then be assigned as the event handler.

If you want to assign a function, then you need to pass the function itself.

...onclick = myFunction;

If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.

...onclick = function () {
        myFunction("arguments");
    };

Instead of assign you invoke a function with myFunction(); Use it like this

//bind event listener
 function initialize(){
    document.getElementById("thediv").onclick = function(){
         myFunction(" something ");
   }
 }

Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...

//bind event listener
        function initialize(){
             document.getElementById("thediv").onclick = function () { myFunction(" something "); };    
        }
//end of bind

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