jquery在循环中选择元素

时间:2012-01-17 08:15:12

标签: jquery

目前我在循环中有这个隐藏的输入,它可以工作:

<input type="hidden" class="md" name="business-222" value="11|55|some name| some address|800-444-8800|somepage.html" />

<input type="hidden" class="results" name="business-222" value="22|77|other name| other address|800-444-8800|otherpage.html" />


$(".results").each(function(){
  var text = $(this).attr('value').split('|');
  var name = text[2];
  ...
});

我想知道在不使用隐藏元素的情况下从这个结构获取数据的好方法..

<tr>
  <td><a href="/somepage.html">some name</a></td>
  <td>some address</td>
  <td>some phone</td>
</tr>

<tr>
  <td><a href="/otherpage.html">other name</a></td>
  <td>other address</td>
  <td>other phone</td>
</tr>

我想要制作并以某种方式选择第一个第二个第三个td?

谢谢!

4 个答案:

答案 0 :(得分:1)

我想知道如何在不使用隐藏元素的情况下从这个结构中获取数据的好方法..

尝试:

$("#tableID > tbody > tr").each(function(){
  var first = $("td:eq(0)", $(this)).html();
  var second = $("td:eq(1)", $(this)).html();
  var third = $("td:eq(2)", $(this)).html();

  alert(first);
  alert(second);
  alert(third);

});

Working Example

答案 1 :(得分:0)

我认为你需要这样的东西:

$('table tr').each(function(index, elem) {
    $(this).find('td').each(function(index, elem) {
        var obj = {};
        switch(index) {
        case 0:
            obj.name = $(this).find('a').text();
            break;
        case 1:
            obj.address = $(this).text();
            break;
        case 2:
            obj.phone = $(this).text();
            break;
        }

        // do something here with the obj, for example put it in a global array or so
    });
});

答案 2 :(得分:0)

为什么不直接输出您需要的数据作为JS对象? 例如:

    data = {};
    data.poi1 = {
        val1    : 11,
        val2    : 55,
        name    : 'some name',
        address : 'some address',
        phone   : '800-444-8800',
        page    : 'somepage.html'
    };
    data.poi2 = {
        val1    : 22,
        val2    : 77,
        name    : 'other name',
        address : 'other address',
        phone   : '800-444-8800',
        page    : 'otherpage.html'
    };
    alert(data.poi1.val1);

答案 3 :(得分:0)

Thanks for all the answers Its working now just have a minimal hidden for lat/long will clean up that later..

<tr class="results">
<td><div class="m maps" id="ms_1"></div><input type="hidden" class="geo" name="business-12345" value="32.9131|-96.8822" /></td>
<td><a href="/architects">Architects</a></td>
<td>123456 Abc Ln, Dallas, TX 75056, USA</td>
<td>888-222-0099</td>
</tr>


$(".results").each(function() {
    var coords = $("td:eq(0)", $(this)).find('.geo').attr('value').split('|');
    var name = $("td:eq(1)", $(this)).html();
    var address = $("td:eq(2)", $(this)).html();
    var phone = $("td:eq(3)", $(this)).html();
    var latlng = new google.maps.LatLng(coords[0], coords[1]);
    var marker = createMarker(latlng, '<span class="fs10"><strong>'+name+'</strong><br />'+address+'<br />'+phone+'</span>');
});