You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery遍历指定class元素执行复制函数异常问题求助

代码存在的3个核心问题
  • 未等待DOM加载完成就执行逻辑:JS运行时页面元素还未渲染,jQuery无法选中目标节点,所有操作都不会生效。
  • 元素ID取值错误:each回调内的this是原生DOM对象,不是ID字符串,直接拼接字符串会得到无效选择器,匹配不到关联的PrintHelp div。
  • 逻辑方向和API使用错误:
    • 现有代码是把PrintHelp元素的内容写入textarea,和“textarea内容复制到PrintHelp div”的需求完全反向
    • val()仅用于表单元素取值/赋值,普通div操作文本内容需要用text()方法
修复后完整代码

HTML(无需调整)

<textarea class="TextArea" id="TextArea1">Text in block 1</textarea>
<div class="PrintHelp" id="TextArea1PrintHelp"></div>
<br/><br/><br/><br/><br/>
<textarea class="TextArea" id="TextArea2">Text in block 2</textarea>
<div class="PrintHelp" id="TextArea2PrintHelp"></div>

jQuery代码

// 等DOM全部渲染完成后再执行逻辑
$(function() {
  function copy_to_print_helper(TextAreaID, PrintHelpID){
    // 取textarea的值,设置为对应PrintHelp div的文本
    $('#' + PrintHelpID).text($('#' + TextAreaID).val());
  }
  
  $('.TextArea').each(function(){
    // 传入当前textarea的id,拼接得到对应div的id
    copy_to_print_helper(this.id, this.id + 'PrintHelp')
  })
})

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 18:39:27