0

我有以下 HTML 标记:

<table>
    <tr>
        <th><label>Item Name</label></th>
        <th><label>Quantity</label></th>
     </tr>
    <tr>
        <td><input type="text" class="itemized-list-item" size="20"/></td>
        <td><select>
                <option class="quantity" value="1">1</option>
                <option class="quantity" value="2">2</option>
                <option class="quantity" value="3">3</option>
                <option class="quantity" value="4">4</option>
                <option class="quantity" value="5">5</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="text" class="itemized-list-item" size="20"/></td>
        <td><select>
                <option class="quantity" value="1">1</option>
                <option class="quantity" value="2">2</option>
                <option class="quantity" value="3">3</option>
                <option class="quantity" value="4">4</option>
                <option class="quantity" value="5">5</option>
            </select>
        </td>
    </tr>
</table>

我尝试了以下方法来获取输入类型中的项目值和下拉列表中的选定数量选项:

var quantity;
var item;
$('.itemized-list-item').each(function() {
    item = $(this).val();
    quantity = $(this).next('.quantity:selected').attr('value');
}

我得到了项目值,但没有得到选定的选项。

我已经尝试了几个小时的许多方法,但无济于事。我希望有人可以阐明我哪里出错了。

干杯,导航

4

3 回答 3

4

如果您要遍历输入,那么获取相关选择元素的一种方法是从当前输入向上导航到最近的 tr,然后返回到选择:

var quantity;
var item;
$('.itemized-list-item').each(function() {
    item = $(this).val();
    quantity = $(this).closest('tr').find('select').val();
    // do something with item and quantity
});

Your use of .next('.quantity:selected') didn't work because the .next() method doesn't search through the document looking for the next matching element, it simply selects the immediate following sibling if there is one and it matches the selector you supplied and otherwise selects nothing.

于 2013-02-06T11:39:57.507 回答
1

试试这个:

var quantity;
var item;
$('.itemized-list-item').each(function() {
    item = $(this).val();
    quantity = $(this).parent().next.find('.quantity:selected').attr('value');
}
于 2013-02-06T11:37:42.723 回答
1
var quantity,
    item;

$('.itemized-list-item').each(function() {
    item = this.value;
    quantity = $(this).parent().next().find('select').val();
});
于 2013-02-06T11:40:10.533 回答