开发者

appending multipleDIVs to multiple TDs using jquery

I have a TR with 5 TD's in it. now I want to add to each of the last 3 TDs a series of divs with data taken from an array:

arr=[   
{Div1Data:'text1a',Div2Data:'text2a',Div3Data:'text3a'},
{Div1Data:'text1b',Div2Data:'text2b',Div3Data:'text3b'},
{Div1Data:'text1c',Div2Data:'text2c',Div3Data:'text3c'}  
];

so I have

var tds=$('td',myTR).slice(2,4);

 how do I addppend the 3 divs to each td to eventually get something like:

<tr>
   <td>foo</td>
   <td>bar</td>
   <td><div>text1a</div><div>text1b</div><div>text1c</div></td>
   <td><div>text2a</div><div>text2b</div><div>text2c</div></td>
   <td><div>text3a</div><div>text3b</div><div>开发者_如何学编程;text3c</div></td>
</tr>

please note that I would also like to bind a click event to each such div, so I con't want to compose the HTML but rather build the actual elements.

Thanks


tds.each(function() {
    var index=0;
    for (var prop in arr[index]) {
        if (arr[index].hasOwnProperty(prop)) {
            $(this).append($('<div>'+arr[index][prop]+'</div>'));
        }
    }
    index++;
});

(sorry about the many edits... brain not working too good this am)

http://jsfiddle.net/WR3GA/12/

Just noticed your note about binding - if you are going to bind right as you create the elements, just assign them to an interim variable

    var el = $('<div>'+arr[index][prop]+'</div>');
    el.bind(...);
    $(this).append(el);

You could also just use a selector afterwards which is probably easier.


this is the code I came up: http://jsfiddle.net/y5TQF/5/

for(var i=0; i<arr.length; i++)
{
    var div = $("<div />").html(arr[i].Div1Data);
    div.click(function() { /* click handler */ });
    $('table tr td').eq(3).append(div);
}

you can do the same for 4th and 5th td.


you can try : http://jsfiddle.net/rxjNf/1/

$(function(){

addContent('Div1Data',2);
addContent('Div2Data',3);
addContent('Div3Data',4);

});

 function addContent(p,tdIndexNumber)
    {
    for(var i=0; i<arr.length; i++)
    {
      var div = $("<div />").html(arr[i][p]);
      div.click(function() { /* click handler */ });
      $('table tr td:eq('+tdIndexNumber+')').append(div);
    }
}

AND This example : http://jsfiddle.net/rxjNf/2/ [Will get each row in table and add content]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜