javascript - 如何在 div 中找到第一个 id

标签 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>

最佳答案

我建议:

// 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');

引用资料:

关于javascript - 如何在 div 中找到第一个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23343608/

相关文章:

javascript - 了解从 JS 中的 event.acceleration 接收到的设备运动数据

javascript - 添加 EmojiOne 区域后字符计数器中断

javascript - 如何从网站执行批处理文件

javascript - jvectormap标记颜色问题

javascript - 导航栏元素不折叠

javascript - 隐藏最大高度的内容以隐藏下拉列表

javascript - 让文本区域正确计算换行符

javascript - 使用 JavaScript/jQuery 返回基于高亮文本的 CSS 选择器列表

javascript - 如何在 Angular 动态表单字段内添加动态表单字段?

javascript - 在没有服务器端、silverlight、DBC 等的情况下处理 SharePoint Intranet 跨域的最佳方法