2017-09-20 8 views
-1

サンプルコード。ここで他の配列に配列されている配列に対して、document.getelementをidで使用する方法

<script> 
    var app = (function() { 
    var config = { 
     X:345, 
     Y:543, 
     Z: [ 
     [1,3], 
     [2,4], 
     [3,6] 
     ] 
    }; 
    }()); 
</script> 

私は入力フィールドから動的Zに値を渡したいです。どうすればいいですか? onclickイベントを使ってhtmlからそのような種類のオブジェクトにアクセスする方法。 可能であれば、サンプルやhtml、jsコードのサンプルを提供してください。ありがとう。

+1

イベントハンドラを追加しますか? – Li357

答えて

0

入力フィールドに入力した値に基づいて値がZに追加される例を作成しました。私はあなたの質問に答えることを願っています。

var app = (function() { 
 
    var config = { 
 
    X:345, 
 
    Y:543, 
 
    Z: [ 
 
     [1,3], 
 
     [2,4], 
 
     [3,6] 
 
    ] 
 
    }; 
 
    
 
    function onFormSubmitted(event) { 
 
    // Prevent the browser from actually submitting the form. 
 
    event.preventDefault(); 
 
    
 
    const 
 
     input = document.getElementById('input'); 
 
    // Make sure the input was found and it has a value in it. 
 
    if (input === null || input.value === '') { 
 
     return; 
 
    } 
 
    
 
    // Push the value in the input into Z. 
 
    config.Z.push(input.value); 
 
    // Reset the form. 
 
    event.target.reset(); 
 
    } 
 

 
    function logConfig() { 
 
    console.log(config); 
 
    } 
 

 
    function init() { 
 
    const 
 
     form = document.getElementById('form'); 
 
     
 
    if (form !== null) { 
 
     // Listen for the submit event to add the value in the input to Z. 
 
     form.addEventListener('submit', onFormSubmitted); 
 
    } 
 
    } 
 
    
 
    
 
    init(); 
 
    
 
    // Return the logConfig method so it can be called from outside. 
 
    return { 
 
    logConfig 
 
    } 
 
}()); 
 

 
const 
 
    logButton = document.getElementById('log'); 
 
// Whenever the log button is clicked, log the current app config. 
 
logButton.addEventListener('click', event => { 
 
    app.logConfig(); 
 
});
<form id="form"> 
 
    <input type="number" id="input"/> 
 
    <button>Add number</button> 
 
</form> 
 

 
<button id="log" type="button">log config</button>

関連する問題