wordpress ACF自定义块内的jQuery无法选择块外的元素

时间:2019-03-20 14:09:56

标签: javascript jquery wordpress advanced-custom-fields wordpress-gutenberg

我有一个像这样的高级自定义字段gutenberg块模板:

<article class="m04x">
    <hr>
    <div class="row">
        <div class="col-md-12">
            <h4>On this site:</h4>
            <ol id="anchor_list">
            </ol>
        </div>
    </div>
</article>

<script>

    (function($) {
        var anchor_list = $('#anchor_list');
        $('.anchor-block').each(function() {
            var heading_text = $(this).html();
            var href = '#' + $(this).attr('id');
            var html = '<li class="nav-item"><a class="fontstyle" href="' + href + '">' + heading_text + '</a></li>';
            anchor_list.append(html);
        });
    })(jQuery);

</script>

使用以下方式注册:

function register_on_this_site_block() {
    if ( function_exists( 'acf_register_block' ) ) {
        acf_register_block(array(
            'name'            => 'on-this-site-block',
            'title'           => __( 'On This Site Block', 'wds'),
            'description'     => __( 'Links to parts of current page.', 'wds'),
            'render_template' => get_template_directory() . '/template-parts/blocks/on_this_site.php',
            'category'        => 'layout',
            'icon'            => 'align-center',
            'mode'            => 'preview',
            'keywords'        => array('links'),
        ));
    }
}
add_action( 'acf/init', 'register_on_this_site_block' );

JQuery似乎可以选择“ #anchor_list”,因为它在同一模板中。但是,当选择“ .anchor-block”时,它将返回一个长度为0的对象,而“ each”功能则什么也不做。

如何访问此块之外的元素?实际上应该提到,“。anchor-block”元素位于另一个自定义ACF块中。

1 个答案:

答案 0 :(得分:0)

正如Taplar所说,当我试图选择元素时,我选择的元素并不存在。我以为我的(function($) { })(jQuery)函数在页面完全加载后正在运行,但实际上并未运行。我将代码更改为此,并且有效:

    var $ = (jQuery);
    $(window).bind("load", function() {
        var anchor_list = $('#anchor_list');
        $('.anchor-block').each(function() {
            var heading_text = $(this).html();
            var href = '#' + $(this).attr('id');
            var html = '<li class="nav-item"><a class="fontstyle" href="' + href + '">' + heading_text + '</a></li>';
            anchor_list.append(html);
        });
    });

尽管您可以在填充<li>元素之前一瞬间看到空白列表,但这对我来说很好。