Pass javascript function as data-* attribute and execute

前端 未结 4 788
甜味超标
甜味超标 2021-02-11 18:21

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

4条回答
  •  隐瞒了意图╮
    2021-02-11 18:59

    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

提交回复
热议问题