javascript - 为什么在使用 AJAX 加载 html 后 jQuery 更改函数不起作用?

标签 javascript jquery ajax

我加载一个表单并通过 AJAX 从 PHP 文件动态填充一个选择。在实现动态 AJAX 填充选择之前,我的更改功能有效(当用户选择“其他”时它只显示另一个输入)。现在更改功能不起作用。

我知道 ready 函数正在触发,因为 jStepper 函数正在运行。我已经在 ready 函数内外使用 change 函数进行了尝试。我感觉更改功能在 AJAX 获取完成之前加载,但这真的重要吗?

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();
        }
    });
});

最佳答案

修改这个:

$('#ve_categoryNo').change(function() { 

$(document).on('change', '#ve_categoryNo', function() { 

EDIT3:在更仔细地检查您的代码后,这将表现最佳:

   $('#ve_categoryNo_td').on('change', '#ve_categoryNo', function() {

因为它最接近相关元素。


我认为您还应该将 ajax 调用放入准备好的脚本中。

发生这种情况的原因是 DOM 中没有任何东西可以在实例化时绑定(bind)到。以这种方式使用 .on 会将其绑定(bind)到文档。如果您有另一个包装它的“固定”元素,最好使用它来代替“文档”来绑定(bind)到它,因为它可能会表现得更好。

编辑:请注意,在将元素作为 ajax 调用完成的一部分注入(inject)之后,您还可以添加更改事件管理,但是如果您多次执行此操作,那么在这种情况下您应该先解除绑定(bind)。

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.

关于javascript - 为什么在使用 AJAX 加载 html 后 jQuery 更改函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9929600/

相关文章:

jquery - 获取多个ajax请求的总数

javascript - Node.js中的setTimeout

javascript - 在 D3 v5 中以编程方式停止 dragmove 事件

javascript - 使用 Webpack 将 Less 文件编译成单独的 css 文件

javascript - javascript 函数后括号中的值

jquery - 如何定义raty "score"变量传递给php脚本?

javascript - d3 强制拖动布局上的多个拖动功能

javascript - 在 javascript 中引用弹出窗口的直接父级

javascript - JSONP 与 XML 一起使用?

PHP-JavaScript : Monitor changes of a file