如何在div中找到第一个id

时间:2014-04-28 14:20:58

标签: javascript jquery

我正在尝试创建需要此表单中的id的脚本。我想在otf_itm类中找到第一个id。所以在这种情况下我正在寻找要返回的town_id。我尝试了一些不同的选择,但到目前为止他们都回来了未定义的

$('.otf_itm:first-child').attr('id');
$('.otf_itm').find('id');
$('.otf_itm').find().attr('id');

<div class="otf_itm">
    {if $towns|@count gt 0}
    <select class="form-control chosen add_town" name="town_id" id="town_id" data-rule-required="true" data-placeholder="Choose a town">
        <option value=""></option>
        {foreach $towns as $town}
        <option value="{$town.id}" {if $town.id eq $form_data.town_id}selected="selected"{/if}>{$town.town_name}{if $town.region_name}, {$town.region_name}{/if}</option>
        {/foreach}
        <option value="ADD_NEW">Add new town...</option>
    </select>
    {else}
    <p class="mt5">You have no towns configured.</p>
    <p class="mt5"><a href="#modal-1" role="button" id="town_id" class="showhouse-text" data-toggle="modal">Add new town</a></p>
    {/if}
</div>

2 个答案:

答案 0 :(得分:2)

使用此:

$('.otf_itm [id]:first-child').attr("id")

当然,当您的模板语言正确地将其呈现为有效的html输出时,上述方法仍然有效。

答案 1 :(得分:2)

我建议:

// selects elements with an id attribute within the .otf_itm element:
$('.otf_itm [id]')
// retrieves the first:
.first()
// gets the id property from that jQuery object:
.prop('id');

或者:

// selects elements with an id attribute within the .otf_itm element:
$('.otf_itm [id]')
// retrieves the first:
.eq(0)
// gets the id property from that jQuery object:
.prop('id');

参考文献: