javascript 为什么使用 AJAX 加载 html 后 jQuery 更改功能不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9929600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't a jQuery change function work after loading html with AJAX?
提问by ahhchuu
I load a form and dynamically populate a select via AJAX from a PHP file. Before implementing the dynamic AJAX populated select, my change function works (it just shows another input when a user selects 'other'). Now the change function does not work.
我加载一个表单并通过 AJAX 从 PHP 文件动态填充一个选择。在实现动态 AJAX 填充选择之前,我的更改功能有效(当用户选择“其他”时,它仅显示另一个输入)。现在更改功能不起作用。
I know the ready function is firing because the jStepper functions run. I have tried this with the change function in and outside the ready function. I have a feeling the change function loads before the AJAX get is finished, but does that really matter?
我知道就绪函数正在触发,因为 jStepper 函数正在运行。我已经尝试过使用就绪函数内外的更改函数。我有一种感觉,在 AJAX get 完成之前更改函数会加载,但这真的很重要吗?
var types = "<select name='ve_categoryNo' id='ve_categoryNo'>";
var d = new Date();
$.get('scripts/vehicle_category_feed.php?date=' + d.getTime(), function ($type)
{
$($type).find('type').each(function ()
{
types += "<option value='" + $(this).attr("categoryno") + "'>" + $(this).attr("category") + "</option>";
});
types += "<option value='other'>Other(Specify)</option></select>";
$('#ve_categoryNo_td').html(types);
});
$(document).ready(function ()
{
$('input[type=text]').click(function ()
{
$(this).select();
});
$('#vehicle_entry').ajaxForm(function ()
{
showMessage('vehicle_information_added');
});
$('#ve_ariNo').jStepper({minValue: 1, maxValue: 99999999});
$('#ve_fleetNo').jStepper({minValue: 1, maxValue: 999999999});
$('#ve_vehicleYear').jStepper();
$('#ve_purchasePrice').jStepper({minValue: 0});
$('#ve_categoryNo').change(function ()
{
if ((this.value) == "other")
{
$('#otherCategory').show();
$('#otherCategory input[type=text]').focus();
} else
{
$('#otherCategory').hide();
}
});
});
回答by Mark Schultheiss
modify this:
修改这个:
$('#ve_categoryNo').change(function() {
to
到
$(document).on('change', '#ve_categoryNo', function() {
EDIT3: This would perform the best after an examination of your code more closely:
EDIT3:在更仔细地检查您的代码后,这将表现最佳:
$('#ve_categoryNo_td').on('change', '#ve_categoryNo', function() {
as it binds closest to the element in question.
因为它绑定的最接近相关元素。
You should also put the ajax call inside the ready script I would think.
您还应该将 ajax 调用放在我认为的就绪脚本中。
The reason this is occuring is that there is nothing in the DOM to bind to when it is instantiated. Using the .on in this manner binds it to the document instead. If you had another "fixed" element that wraps it, it might be better to bind to that using that in place of "document" as it would likely perform better.
发生这种情况的原因是 DOM 中没有任何东西在实例化时绑定到。以这种方式使用 .on 会将其绑定到文档。如果您有另一个包装它的“固定”元素,最好使用它代替“文档”绑定到它,因为它可能会表现得更好。
EDIT: Note that you COULD also add the change event management after you inject the element as part of the ajax call completion, but if you do this more than once, you should unbind it first in that case.
编辑:请注意,在将元素作为 ajax 调用完成的一部分注入后,您还可以添加更改事件管理,但如果您多次执行此操作,则在这种情况下应先解除绑定。
EDIT2: since there are questions/comments: FROM THE DOCUMENTATION: http://api.jquery.com/on/
EDIT2:因为有问题/评论:来自文档:http: //api.jquery.com/on/
Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.
在文档树顶部附近附加许多委托的事件处理程序会降低性能。每次事件发生时,jQuery 必须将该类型的所有附加事件的所有选择器与从事件目标到文档顶部的路径中的每个元素进行比较。为了获得最佳性能,请在尽可能靠近目标元素的文档位置附加委托事件。避免过度使用 document 或 document.body 来处理大型文档的委托事件。
回答by Walter Stabosz
I think the element you are binding to in the line:
我认为您在行中绑定的元素:
$('#ve_categoryNo').change(function() { ...
does not yet exist in the DOM, so the event does not get bound.
DOM 中尚不存在,因此事件不会被绑定。
Try using the .livefunction:
尝试使用.live函数:
$('#ve_categoryNo').live('change', function() { ... });
Or make sure that your DOM elements exist before you try to bind events to them.
或者在尝试将事件绑定到它们之前确保您的 DOM 元素存在。
回答by Vinoth Smart
Worked from document ready to change works Ajax functionality
从准备好更改工作的文档开始工作 Ajax 功能
$(document).change(function(){
$("#next").click(function() {
var questionid = $('#question').val();
var assementid = $('#assement').val();
var userid = $('#user').val();
if($('.ansradio').is(':checked')) {
var answer = $('input[name=ans]:checked', '#questionajax').val();
$.ajax({
type: "POST",
url: "answer/",
data: "q_id="+questionid+"&a_id="+assementid+"&answer="+answer+"&user_id="+userid,
success: function(html){
$("#questionajax").html(html).show();
}
});
}
else{
alert("Please answer the questions");
}
});
});
});