根据单击循环中的哪个按钮填充字段

Populate field depending on which button in a loop has been clicked

我有一个使用高级自定义字段的自定义循环,它显示三个框,每个框都有内容。

如果框 1 中的按钮已被选中,我希望框 1 中的内容填充到输入中。

如果框 2 中的按钮已被选中,我希望框 2 中的内容填充到输入中,依此类推。

我的html如下:

<div class="row">
    <?php if( have_rows('event') ): while ( have_rows('event') ) : the_row(); ?>
        <div class="four">
            <div class="input"><?php the_sub_field('details'); ?></div>
            <a class="button btn" href="#contact">Make an appointment</a>
        </div>
    <?php endwhile; else : endif; ?>
</div>

<input id="output"></input>

我的 jQuery 是:

jQuery(document).ready(function($) {
    $(".btn").click(function(e) {
        $("#output").val($(".input").val());    
    });
});

我已经设法为一个盒子找到了可行的解决方案,但没有找到一个循环的解决方案,我怀疑这可能与 .each() 有关,但我不确定。

谢谢。

你只需要获取点击按钮的同级输入即可。但是,您确实需要将 div class="input" 设为实际的 input 才能使 .val() 正常工作。否则,您将不得不使用 .text() 来获取 div.

中的文本
jQuery(document).ready(function($) {
    $(".btn").click(function(e) {
        $("#output").val($(this).siblings('.input').val());    
    });
});

你的 jQuery 非常接近。

有两个问题:

  1. 您正在尝试使用 div.val(),它没有 value - 它有 text(或 html ), 所以你需要使用 .text() (or .html()).就您而言,我相信 .text 就是您所追求的。
  2. 如果 first .input 元素需要相关的 .input 元素,则将值放入输入中到点击的按钮。有几种方法可以做到这一点,但在您的情况下,最直接的方法是使用 .siblings.

    // Short-hand document ready (which is no-conflict safe, necessary in WP scripts)  
    jQuery(function($) {
        $(".btn").click(function(e) {
            // $(this) is this button - get the sibling .input element's text
            $("#output").val($(this).siblings(".input").text());    
        });
    });