如何通过点击按钮获取对应前置input的id(优先jQuery方案)
解决方法:通用jQuery获取对应Input的ID
嘿,我明白你的困扰了——之前用closest和sibling没成功,核心原因是按钮和目标input根本不在同一个父容器里,这俩方法自然找不到目标元素!
先看你的结构:input在col-sm-3的div里,按钮在单独的row下的col-sm-1里,它们是同级的“兄弟容器”,不是直接的兄弟元素。所以得换个思路,先找到它们共同的层级关联,再定位input。
方案一:利用容器的同级关系定位
针对你给出的HTML结构,直接用以下通用代码就行:
$('.btn-get-infos').click(function() { // 步骤:1. 找到按钮所在的row容器 → 2. 获取它的前一个同级容器(就是装input的那个col-sm-3) → 3. 找到里面的input并取id const targetInputId = $(this).closest('.row').prev().find('input').attr('id'); console.log('对应的Input ID:', targetInputId); // 这里可以写你后续要执行的逻辑,比如用这个ID做操作 });
方案二:给每组加统一父容器(更健壮)
如果后续你的页面结构可能调整,建议给每组input+按钮套一个统一的父容器,比如:
<!-- 每组都套一个这个容器 --> <div class="input-btn-group"> <div class="col-sm-3"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-link"></i></span> </div> <input type="text" name="first_map_link" class="form-control" id="first_map_link" placeholder="Lien première map..."> </div> </div> <div class="row"> <div class="col-sm-1"> <button class="btn btn-outline-info btn-get-infos"><i class="fas fa-search"></i></button> </div> </div> </div>
然后用closest找到这个父容器,再找里面的input,这样结构调整也不容易出错:
$('.btn-get-infos').click(function() { const targetInputId = $(this).closest('.input-btn-group').find('input').attr('id'); console.log('对应的Input ID:', targetInputId); });
额外小贴士
- 如果你的容器里可能有多个input,可以给目标input加个专属类(比如
target-input),然后把find('input')改成find('input.target-input'),避免取错元素。 - 可以加个判断,确保找到input后再执行逻辑,比如:
const $targetInput = $(this).closest('.row').prev().find('input'); if ($targetInput.length) { const inputId = $targetInput.attr('id'); // 你的逻辑 }
内容的提问来源于stack exchange,提问作者XeloOw
相关产品推荐
相关产品推荐

