如何将值从javascript传递到HTML,反之亦然

时间:2017-04-02 10:20:15

标签: javascript html

我想按照以下方式做:

  1. 获取配对值列表 - 每个值包含名称和数字
  2. 向用户显示按钮列表,每个按钮显示名称 - 值对中的名称,因此如果我得到10对,我将显示10个按钮
  3. 当用户单击所选名称时,该按钮将调用名称 - 值匹配的JS。
  4. 我对HTML很新,所以这部分对我来说是个问题。 在这个阶段,页面不需要看起来很好,只是正常运行。

    <html>
    
    <head> </head>
    
    <body>
        <script>
        var pairs = [
            {
                "name_1": 123
            },
            {
                "name_2": 983
            },
            {
                "name_3": 567
            }
        ];
    
        function present_buttons(pairs) {
            for (var i in pairs) {
                console.log(`index  = ${i}`);
                console.log(`name  = ${pair[i].name}`);
                console.log(`value  = ${pair[i].value}`);
                // send info the the HTML section, so present proper names on buttons
                // make sure to hook matching value for each button so it will be sent correctly to the use_value function later on
            }
        }
    
        function use_value(value) {
            // do something with the value triggered by the matching name button
        }
        </script>
        <!--
    get names to present on buttons from the present_buttons()
    when a button is clicked , send the matching value to the use_value() function
    
    -->
    </body>
    
    </html>
    

1 个答案:

答案 0 :(得分:1)

试试这个:

<html>
    <head></head>
    <body>
        <script>
            var pairs = [
                { "name_1" : 123 } , 
                { "name_2" : 983 } , 
                { "name_3" : 567 } 
            ];

            for (var i = 0; i < pairs.length; i++) {
                var button = document.createElement('button');
                var pair = pairs[i];

                button.innerHTML = Object.keys(pair)[0];
                button.addEventListener('click', function (pair) {
                    use_value(pair);
                }.bind(this, pair));

                document.getElementsByTagName('body')[0].appendChild(button);
            }


            function use_value(value)  {

                // do something with the value triggered by the matching name button
            }
        </script>
    </body>
</html>