Pass javascript function as data-* attribute and execute

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

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

5条回答
  •  情话喂你
    2021-02-11 18:38

    You can just bind a function as a data attribute

    const ele = $('button');
    
    ele.data('onClick', evt => {
        alert('bye');
    })
    
    ele.click(evt => {
        const ele = $(evt.target);
        ele.data('onClick')(evt);
    })
    

提交回复
热议问题