jQuery多属性筛选问题:点击COPY按钮无法复制数据至表单
完整解决方案
1. Python生成HTML的代码
用Python生成结构清晰的HTML文件,给需要获取数据的元素添加类名,方便jQuery准确定位:
# 生成HTML的Python代码 html_content = """ <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>数据复制示例</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <style> table { border-collapse: collapse; margin-top: 20px; } th, td { border: 1px solid #ccc; padding: 8px 12px; } .form-group { margin-bottom: 10px; } .form-group label { display: inline-block; width: 80px; } button { cursor: pointer; } </style> </head> <body> <div class="form-container"> <div class="form-group"> <label for="item-input">Item:</label> <input type="text" id="item-input" name="item"> </div> <div class="form-group"> <label for="shopname-input">Shopname:</label> <input type="text" id="shopname-input" name="shopname"> </div> </div> <table> <thead> <tr> <th>Item</th> <th>Shopname</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td class="item-data">商品A</td> <td class="shopname-data">店铺X</td> <td><button class="copy-btn">COPY</button></td> </tr> <tr> <td class="item-data">商品B</td> <td class="shopname-data">店铺Y</td> <td><button class="copy-btn">COPY</button></td> </tr> <tr> <td class="item-data">商品C</td> <td class="shopname-data">店铺Z</td> <td><button class="copy-btn">COPY</button></td> </tr> </tbody> </table> <script> $(function() { // 修正后的jQuery事件处理逻辑 $('.copy-btn').on('click', function() { // 定位当前按钮所在的表格行 const $currentRow = $(this).closest('tr'); // 获取当前行的目标数据 const itemText = $currentRow.find('.item-data').text().trim(); const shopnameText = $currentRow.find('.shopname-data').text().trim(); // 将数据填入表单输入框 $('#item-input').val(itemText); $('#shopname-input').val(shopnameText); }); }); </script> </body> </html> """ # 写入HTML文件 with open('data_copy.html', 'w', encoding='utf-8') as f: f.write(html_content)
2. 选择器问题修正说明
之前返回undefined的核心问题是选择器未限定到当前点击按钮所在的行,比如直接用$('.item-data').text()会获取页面中第一个匹配元素的内容,而非当前行的数据。
修正逻辑:
- 用
$(this)获取当前点击的COPY按钮 - 调用
.closest('tr')定位按钮所在的表格行 - 通过
.find('.item-data')和.find('.shopname-data')精准获取当前行的目标数据 - 最后将数据填入对应表单输入框
验证步骤
- 运行上述Python代码,生成
data_copy.html文件 - 用Google Chrome打开该文件
- 点击任意行的COPY按钮,对应行的item和shopname会自动填入上方表单
内容的提问来源于stack exchange,提问作者kazutaka
相关产品推荐
相关产品推荐

