簡體   English   中英

在JavaScript對象文字中使用變量

[英]Using Variable Within JavaScript Object Literal

基本上,我在從輸入框獲取信息並在對象文字中使用該變量時遇到了麻煩。

這是我的代碼:

$("document").ready(function() {

    function updateEvent(){
        render();
    }

    function render() {
                     //get values from input
            var gallons = $("#gallons").val();
            var electricity = $("#electricity").val();
            var energy = $("#energy").val();

        var figure = new Highcharts.Chart({

            series: [{
                    name: 'Throttle',
                    data: [0, 0, 30 , 0, energy, 30, 0, 0] //Variables will not work in here, no specific error but data doesn't show
                }, {
                    name: 'Power',
                    data: [30, 30 , 30, 30, 30, 30, 30, 30]
                }]

        });

我嘗試嵌入一個函數並執行其他技巧,但沒有任何效果,我可能做錯了,我不確定。 有什么方法可以在對象文字中使用變量,而無需完全重新編碼結構。

任何幫助將不勝感激。

如何從輸入框中獲取值並在對象文字中使用該值?

function doStuff(){
      var realIncome = document.getElementById("income").value;
      var objLit= { realIncome: realIncome,
                 desiredIncome: realIncome * 4 };
      console.log(objLit);
      document.getElementById("out").innerText = 
            objLit.realIncome + " " + objLit.desiredIncome;
 }

和HTML

Big Number 
<input id="income" name="income" type="number" 
    placeholder="please enter your desired income">
<button name="calculate" onclick="doStuff()">click me </button>​

Your income <span id="out"></span><br />

請看一下我的演示代碼: http : //jsfiddle.net/mppAM/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM