HTML element with variable

后端 未结 4 1815
鱼传尺愫
鱼传尺愫 2021-01-15 08:08

In jQuery I can create a HTML element with data:

$(\'\').data(\"field\", { i: i, j: j }).appendTo(\"body\");
<         


        
4条回答
  •  滥情空心
    2021-01-15 08:40

    If you want the html of a button which will have the same data available as the button you created, you'll have to use the html5 data attributes. i.e.

    
    

    and read it

     function btn(){
            var field = $('button').data("field");
            alert(field.i)}
     }
    

    with plain js

     function btn(){
            var field = JSON.parse(document.querySelector('button').getAttribute("data-field"));
            alert(field.i)}
     }
    

提交回复
热议问题