如何用jQuery将文本追加到对应.container容器(续篇)
问题描述
我需要实现点击+按钮时,将对应输入框的文本追加到它自己对应的.container容器中,而不会误追加到其他.container里。我的HTML结构如下:
<div class="container"></div> <div class="addTextSection"> <div class="add">+</div> <input class="someText" type="text"> </div> <div class="container"></div> <div class="addTextSection"> <div class="add">+</div> <input class="someText" type="text"> </div>
解决方案
核心是通过DOM层级关系定位当前操作对应的目标容器,避免影响其他同类型元素。以下是实现代码:
$('.add').on('click', function() { // 定位当前按钮所属的addTextSection容器 const currentSection = $(this).closest('.addTextSection'); // 获取该section对应的前一个container容器 const targetContainer = currentSection.prev('.container'); // 获取当前section内输入框的文本 const inputContent = currentSection.find('.someText').val().trim(); // 仅当输入内容非空时追加 if (inputContent) { // 将文本追加到目标容器(可根据需求调整为其他标签,比如<span>) targetContainer.append(`<p>${inputContent}</p>`); // 可选:清空输入框,提升用户体验 currentSection.find('.someText').val(''); } });
关键逻辑说明
closest('.addTextSection'): 从点击的按钮向上查找最近的.addTextSection父元素,确保我们只在当前操作组内处理。prev('.container'): 精准获取当前组对应的.container(即addTextSection的前一个兄弟元素),避免操作其他组的容器。find('.someText'): 仅在当前组内查找输入框,保证拿到的是对应按钮的输入值。
内容的提问来源于stack exchange,提问作者dtd439
相关产品推荐
相关产品推荐

