Pass javascript function as data-* attribute and execute

前端 未结 5 675
陌清茗
陌清茗 2021-02-11 18:31

We know such syntaxes as below, when defining a value for onClick attribute:

5条回答
  •  离开以前
    2021-02-11 18:41

    One way is to use eval()

    jQuery(".container").on("click", "button.marker", function (e) {
        var callback = jQuery(e.currentTarget).data("callback");
    
        var x = eval(callback)
        if (typeof x == 'function') {
            x()
        }
    });
    

    Demo: Fiddle

    Note: Make sure it is safe in your environment, ie there is no possibility of script injection because of bad input from users

    • Why is using the JavaScript eval function a bad idea?
    • When is JavaScript's eval() not evil?
    • eval() isn’t evil, just misunderstood
    • Eval is Evil, Part One

提交回复
热议问题