jQuery $ .each用于动态插入的数据不起作用

时间:2013-11-26 10:02:06

标签: javascript jquery each

我在AJAX调用中使用<ul>动态插入.html()和列表项。我想计算动态插入的<ul>中的列表项数。

代码:

<div id='layout'>
        <a href='javascript:void(0);' class='close'><img src='images/close.png' width='17' /></a>
        <div id='buslayout'></div>
        <div id='boarding'>
            <select name='boarding' id='boarding'>
                <option value=''>Boarding points</option>
            </select>
        </div>
        <div class='seats'><p>Selected seats: <span id='totalseats'></span></p></div>
        <div class='seats'><p>Total: <span id='total'></span></p></div>
        <div class='seats'><p><input type='submit' value='Continue booking' /></p></div>
        <div class='clear'></div>
    </div>

jQuery的:

$('#buslayout').html(data);

$('ul li').each(function(){
    price += parseInt($(this).attr('price'));
    console.log($(this).attr('price'));
});

动态生成的html。

<ul>
    <li price='100'>Bus</li>
    <li price='200'>Bus</li>
    <li price='250'>Bus</li>
    <li price='450'>Bus</li>
</ul>

2 个答案:

答案 0 :(得分:2)

统计列表项?

$('#buslayout').html(data).find('li').length

或者,如果你想在循环时这样做:

var liCount = 0;
$('ul li').each(function(){
    price += parseInt($(this).attr('price'));
    console.log($(this).attr('price'));
    liCount ++;
});

答案 1 :(得分:-1)

您是否已将总座位定义为jQuery变量?

$totalseats = jQuery('.seats');

totalseats.each(function() { ...

**Edit**
Then load the file with $.ajax() and iterate over the returned data

$.ajax({
    url: 'your file',
    success: function(data){
         $.each(data, function(){
             // your func
         });
    }
});