Extract & call JavaScript function defined in the onclick HTML attribute of an element(using jQuery attr/prop)

前端 未结 4 1512
春和景丽
春和景丽 2020-12-22 00:18

I am having 2 buttons A & B and I need to call the function defined in onclick HTML attribute of button B but on click of button A.

Also I need to pass an extra

相关标签:
4条回答
  • 2020-12-22 00:30

    To make it simple you can set some global variables/object you want to pass into function as parameters and then call the function and use global variables/object property value.

    What you say ;)

    /* with variables in global scope should be accessible inside function going to call */
    param1 = 1;
    param2 = 2;
    
    /* function definition */
    function functionCalling(){
      /* use values here */
      console.log(param1, param2);
    }
    
    ...
    functionCalling();
    ...
    
    /* with variables in global scope should be accessible inside function going to call */
    param = {property1:1, property2:2};
    
    /* function definition */
    function functionCalling(){
      /* use values here of object */
      console.log(param.property1, param.property1);
    }
    
    ...
    functionCalling();
    ...
    
    0 讨论(0)
  • 2020-12-22 00:38

    You can do it like this, i.e. use attr instead of prop to get the string value of b's onclick, afterwards replace the arguments p,q from the string with p,q,r and then use Function constructor to create an anonymous function with the new body (after replace).

    jQuery('#btn_a').on('click', function(){
        var onclickB = jQuery('#btn_b').attr('onclick'),
            onclickA = Function(onclickB.replace("p,q", "p,q,r"));
        return onclickA();
    });
    

    Note: you can do anything with this approach, just create a regex pattern to replace anything with what you want.

    0 讨论(0)
  • 2020-12-22 00:43

    You need to make the function doSomething like below, pass null for btn_b and pass value for btn_a. Hope this helps.

    HTML

    <input type="button" id="btn_a">  
    <input type="button" id="btn_b">
    

    SCRIPT

    $("#btn_a").on("click", function() {
            return doSomething(p,q,r);
        });
    
    
    $("#btn_b").on("click", function() {
            return doSomething(p,q,null);
        });
    
    
    function doSomething(p,q,r){
            if(r != null){
            //do something for btn_a and return
            } else {
            //do something for btn_b and return
            }
    
        }
    
    0 讨论(0)
  • 2020-12-22 00:44

    <input type="button" id="btn_a" onclick="return doSomething(p,q,r)">

    0 讨论(0)
提交回复
热议问题