2016-07-11 11 views
2

オブジェクトのリストを反復しようとしていて、それぞれのリスト項目をボタンとして作成しようとしています。私は彼らにonclick機能を追加します。私はこのエラーを得た:ここSyntaxError:missing]要素リストの後にオブジェクトのパラメータをonclick関数に渡そうとしたとき

SyntaxError: missing ] after element list

は私のコードです:

box_resources.forEach(function(box){ 
    $("#box-resources-list").append('<li><button type="button" class="list-group-item" onclick="showBoxMarker(' + box + ')">' + box.title + '</button></li>'); 
}); 

その上の任意のアイデア?ありがとう!

答えて

3

問題は、そのような要素を作成するときにboxが文字列に変換されることです。たとえば:showBoxMarker([object Object])を呼び出す

var box = { 
 
    x: 10, 
 
    y: 10, 
 
    w: 5, 
 
    h: 3 
 
}; 
 
console.log('onclick="showBoxMarker(' + box + ')"');
明らか

は、有効な構文ではありません。代わりに、要素を個別に作成し、その要素にイベントハンドラをアタッチする必要があります。

box_resources.forEach(function(box){ 
    var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>'); 

    // Find the button we just made and attach the click handler 
    $listItem.find('button').click(function() { 
     showBoxMarker(box); 
    }); 
    $('#box-resources-list').append($listItem); 
}); 

の作業例:

var showBoxMarker = function(box) { 
 
    alert(box.title); 
 
} 
 

 
var box_resources = [ 
 
    { title: 'Box A' }, 
 
    { title: 'Box B' }, 
 
    { title: 'Box C' }, 
 
    { title: 'Box D' }, 
 
    { title: 'Box E' } 
 
]; 
 

 
box_resources.forEach(function(box){ 
 
    var $listItem = $('<li><button type="button" class="list-group-item">' + box.title + '</button></li>'); 
 

 
    // Find the button we just made and attach the click handler 
 
    $listItem.find('button').click(function() { 
 
    showBoxMarker(box); 
 
    }); 
 
    $('#box-resources-list').append($listItem); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul id="box-resources-list"></ul>

プロヒント:一般的に、それはテンプレートのいくつかの種類から代わりのJSの文字列から新しい要素を作成し、1を作成する方が良いでしょうイベントハンドラを使用して個々の要素のクリックイベントを処理します。

+1

前のコメントを気にしないでください。私は私の側から何かが間違っている。助けてくれてありがとう!それは完全に動作します。プロのヒントは多くの助けになります。私の将来の発展のために覚えておくべき大きなヒントになるでしょう。ありがとう! – zxue

0

JSON.stringify(ボックス)を使用すると、問題を修正できます。 br、

関連する問題