简体   繁体   中英

How to get element from DOM and set onclick event?

I have this html element:

<table id="miniToolbar">
     <tbody>          
        <tr><td>
          <button id="btnStrView" type="button" onclick='parent.ExecuteCommand()' class="button_air-medium">
            <img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png"></button>
          </td></tr> 
    <tbody>
</table>     

as you can see inside button I have on click event:

onclick='parent.ExecuteCommand()'

And I have this JS function:

function isMenuItemMasked(item)
{
    var funcId = '75';

     var elem = document.getElementById('btnStrView');

    return false;
}

as you can see inside function I have variable called funcId.

I need to put this funcId to the on click event:

onclick='parent.ExecuteCommand('75')'

After I fetch element and put it inside elem variable how do I put funcId as parameter to parent.ExecuteCommand() ?

I think you want to set the function argument dynamically. Without using external libraries I would do as follows:

 function runSubmit() { var value = document.getElementById("text").value; document.getElementById("run").addEventListener('click', function() { func(value); }); } function func(value) { console.log(value); } 
 <input id="text" type="text"> <input type="submit" value="Setup Param" onclick="runSubmit()"> <input id="run" type="submit" value="Run with param"> 

How to use this: When you run the snippet, you will see a text input, a Setup Param button and a Run with param button. Insert something in the text input and click Setup Param. After, click on Run with param to see the effect

The input text contains the string that will be used as parameter for func(value) . The update of #run button callback is triggered by the "Setup param", through the runSubmit() callback. This callback adds to the #run element a listener for the 'click' event, that runs a function with the parameter fixed when event occurs.

This is only a MCVE, you should adapt it to your case scenario.

Mh... Actually @jacob-goh gave you this exact solution in a comment while I wrote this...

you can use jquery to call you function from inside the function and pass your variable to that function.

function isMenuItemMasked(item)
{
 var funcId = "75";

$(document).ready(function(){
$("#btnStrView").click(function(){
   parent.ExecuteCommand(funcId);
 });
});
}
function ExecuteCommand(your_var){
    alert(your_var);
    //your code
    }    

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