简体   繁体   English

jQuery即使启用了jQuery也无法更新PHP生成的元素。

[英]jQuery can't update elements generated by PHP, even with on.('click'

I have the following code, which works fine: 我有以下代码,可以正常工作:

for (var i = 0; i < <?php echo count($set); ?>; i ++){

    $('#inc' + i).on('click', function(){
        $('#scratchbox').val('test');
    });         

}

But what I need is this, which isn't working (the only difference is that '#scratchbox' has changed to '#set' + i): 但是我需要的是这不起作用(唯一的区别是“ #scratchbox”已更改为“ #set” + i):

for (var i = 0; i < <?php echo count($set); ?>; i ++){

    $('#inc' + i).on('click', function(){
        $('#set' + i).val('test');
    });         

}

Both the #inc divs and #set textboxes are generated by PHP in the same place and at the same time (technically, in this order: #set1, #inc1, #set2, #inc2, etc.). #inc divs和#set文本框都是由PHP在同一位置和同一时间生成的(技术上,按此顺序:#set1,#inc1,#set2,#inc2等)。 Also, further down I have this, which is able to retrieve the values contained in the #set textboxes just fine when the event handler is a static #submit div: 此外,在事件处理程序为静态#submit div的情况下,它还可以检索#set文本框中包含的值:

$('#submit').click(function(){

    for (var i = 0; i < <?php echo count($set); ?>; i ++){
        sets[i] = $('#set' + i).val();
    }

}); 

What should I change and why? 我应该更改什么,为什么?

Why dont add class names to your elements so you can do something like: 为什么不向您的元素添加类名称,以便您可以执行以下操作:

$(document).on('click', '.click_element', function() {
   var ID = $(this).attr('id');
   $('#set' + ID).val('test');
});

and have for loop separate that creates those click elements with the IDs. 并具有for循环,以使用ID创建那些click元素。

Note that this solution is much faster in terms of execution than having to bind click events within a loop. 请注意,此解决方案在执行方面比必须在循环中绑定单击事件快得多。

By the time your click event handler runs, the value if i is set to its maximum value. 在您的click事件处理程序运行时,如果i设置为其最大值,则该值。 Create an IIFE in your loop to save the value of i for each iteration of your for loop. 在循环中创建一个IIFE,以保存for循环的每次迭代的i值。

For example: 例如:

for (var i = 0; i < <?php echo count($set); ?>; i ++){
    (function (inner_i) {
        $('#inc' + inner_i).on('click', function(){
            $('#set' + inner_i).val('test');
        });         
    })(i);
}

Here's a good read on using an IIFE (Immediately-Invoked-Function-Expression): http://benalman.com/news/2010/11/immediately-invoked-function-expression/ 这是有关使用IIFE(立即调用功能表达式)的良好阅读: http ://benalman.com/news/2010/11/immediately-invoked-function-expression/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM