求助:jQuery修改AJAX动态注入的input元素值无效问题
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

