且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何修复PHP foreach循环中错误地循环的jQuery代码

更新时间:2022-06-03 21:23:28

注意"this"上下文

Take note of the 'this' Context

当事件在jquery中触发时,会将回调函数this上下文设置为触发该事件的元素.

When an event fires in jquery the callback function this context is set to the element which the event was fired from.

jQuery(document).ready(function($) {
    $(".input_img").click(function() {
        // Use `this` to target the event element
        $(this).attr("src", "<?php the_field('acf_numero_image', $related_post->ID); ?>" );
    });
});

建议: 您不应在for each的每次迭代内生成相同的jquery代码.由于您要重复不必要的代码.您可以利用HTML data-* 属性来实现您寻求的结果.

Advice: You shouldn't generate same jquery code inside each iteration of the for each. Since you're repeating unnecessary code. You can harness HTML data-* attributes to achieve the outcome you seek.