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

求助:jQuery修改AJAX动态注入的input元素值无效问题

解决AJAX动态注入元素后无法修改值的问题

Hey there! I see the issue you're running into here—let's break it down and fix it quickly.

问题根源

The core problem is that AJAX requests are asynchronous. Right now, you're trying to set the value of #txt immediately after calling $.ajax(), but at that point, the AJAX request hasn't finished yet, and the <input> element hasn't been added to the DOM. So $('#txt') doesn't find anything, and the val('test') call does nothing.

解决方案

You need to move the code that modifies the input value inside the success callback of your AJAX request. The success function only runs after the AJAX call completes and the new HTML has been injected into .main, so the input element will exist at that point.

Here's your modified code:

$(document).on('click', '#test', function(){ 
  $.ajax({ 
    type: 'get', 
    url: '/echo/html/', 
    success: function(data) { 
      $('.main').html('<input id="txt" type="text" name="title" value="">');
      // 现在input已经存在,可以设置值了
      $('#txt').val('test'); 
    } 
  }); 
});

额外说明

If you ever work with newer async patterns, you could also use async/await with jQuery's AJAX (since it returns a promise), but the above solution is the most straightforward fix for your current code structure. Just remember: any operations that depend on content loaded via AJAX need to wait until that content is actually present in the DOM.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:44:07