2016-03-30 13 views
0

私はJavaScriptを使いましたが、残念ながら学習中です。だから私は車でオブジェクトを持っています:JavaScriptでの更新操作

var cars = [ 
    { 
     image:'http://superbvehicles.com/wp-content/uploads/2015/10/Nissan-GTR-3.jpg', 
     name:'nissan', 
     model:'gtr', 
     hp:565, 
     price:100.000, 
    }, 
    { 
     image:'http://bestcarmag.com/sites/default/files/4700070mitsubishi-lancer-06.jpg', 
     name:'mitsubishi', 
     model:'lancer', 
     hp:380, 
     price:40.000, 
    }, 
    { 
     image:'http://bestcarmag.com/sites/default/files/2048005subaru-impreza-wrx-sti-01.jpg', 
     name:'subaru', 
     model:'impreza', 
     hp:400, 
     price:50.000 
    }, 
    { 
     image:'http://stancewords.stanceworks.netdna-cdn.com/wp-content/uploads/2012/06/datsun-240z-slammed-red.jpg', 
     name:'nissan', 
     model:'fairlady 240z', 
     hp:200, 
     price:70.000 
    }, 
    { 
     image:'https://s-media-cache-ak0.pinimg.com/736x/35/be/6b/35be6b46846e893d332ddfef989614fe.jpg', 
     name:'nissan', 
     model:'skyline', 
     hp:320, 
     price:80.000 
    } 
] 

このオブジェクトからの情報でいっぱいのhtmlテーブル。私はテーブルのすべての行の "編集"ボタンを作成し、それを押すと、行の情報を受け取り、ユーザーが編集できるようにフォームに挿入します。これはそれを行う機能である:

function editCar(i){ 
    var image = cars[i].image; 
    var name = cars[i].name; 
    var model = cars[i].model; 
    var hp = cars[i].hp; 
    var price = cars[i].price; 

    $('#image-edit').val(image); 
    $('#name-edit').val(name); 
    $('#model-edit').val(model); 
    $('#hp-edit').val(hp); 
    $('#price-edit').val(price); 

    var newImage = $('#image-edit').val(); 
    var newName = $('#name-edit').val(); 
    var newModel = $('#model-edit').val(); 
    var newHp = $('#hp-edit').val(); 
    var newPrice = $('#price-edit').val(); 


}; 

だから私の質問は、私は古いものの代わりに、オブジェクトに(フォームでユーザーにより提供された)新しい情報を挿入することができる方法ですか?

P.S.申し訳ありませんが、私の英語が悪いです。

+0

あなたは、長い時間を使用するためのオブジェクトを更新することはできません 'index'(' i').. – Rayon

+0

を使用することができます。それはちょうど実行時間のために働くでしょう。しかし、新しいフォームデータをページに格納し、そこから古いオブジェクトを設計するためにajaxを呼び出すことができます。 –

答えて

2

最初に、インデックスを新しいデータで置き換えたいインデックスがわかるようにインデックスをどこかに保存し、別のすべての関数が共有できる場所に格納する必要があります。この場合、私たちはそれをグローバルな文脈で定義します。そして、あなたがする必要があるすべては、フォーム送信でそれを上書きします:

// Initialise as -1 so we can check that no index is selected 
var currentIndex = -1; 

function editCar(i){ 
    // Set the global variable to this index so we can use it in other functions 
    currentIndex = i; 
    ... 
} 

// I am assuming your form is wrapped in <form id="form"></form> 
$("#form").on("submit", function(event){ 
    // Without preventDefault, the page might get reloaded and therefor reset 
    event.preventDefault(); 
    // This is for safety, to make sure there is an index 
    if(currentIndex >= 0){ 
     cars[currentIndex].image = $('#image-edit').val(); 
     cars[currentIndex].name = $('#name-edit').val(); 
     cars[currentIndex].model = $('#model-edit').val(); 
     cars[currentIndex].hp = $('#hp-edit').val(); 
     cars[currentIndex].price = $('#price-edit').val(); 
    } 
}); 
関連する問題