【问题标题】:Trying to truncate string after it's called by loop via ajax在通过ajax循环调用后尝试截断字符串
【发布时间】:2020-07-13 14:26:12
【问题描述】:

我有一个包含姓名的表格,每个条目的姓氏都需要被截断。迈尔斯戴维斯成为迈尔斯 D。

我通过以下 JS 实现了这一点:

$('.trunc-name').each(function (d, td) {
    $(td).text($(td).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
});

并且td 类设置为trunc-name

<td class="trunc-name"><?php foreach ($resident_name_terms as $object) { echo $object->name; } ?></td>

那些表格内容(实际上是 WP 分类术语)可以通过选择表单进行过滤 - 其选项也被截断。

选择:

if( $terms = get_terms( array(
    'taxonomy' => 'resident_name',
    'orderby' => 'name'
     ) ) ) :
     echo '<select name="resident_name_filter"><option value="" selected="selected">' . __( 'All Residents', 'mv' ) . '</option>';
     foreach ( $terms as $term ) :
         echo '<option class="trunc-name" value="' . $term->term_id . '">' . $term->name . '</option>'; 
     endforeach;
     echo '</select>';
endif;

到目前为止一切正常。问题是,当我通过该列的选择选项(使用 AJAX 构建)更改条件时,新输出的值不会被截断。

查询参数:

$relation = 'AND';
$params = array();
$args['tax_query']['relation'] = $relation;

foreach ( $taxonomies as $tax ) {
    if( isset( $_POST[ $tax . '_filter' ] ) && !empty( $_POST[ $tax . '_filter' ] ) ) {
        $args['tax_query'][] = array(
            'taxonomy' => $tax,
            'field' => 'id',
            'terms' => $_POST[ $tax . '_filter' ],
        );
    }
};

循环:

$query = new WP_Query( $args );
if( $query->have_posts() ) : ?>
    <table style="width:100%" id="incident-reports">
        <tr>
            <th>Resident</th>
        </tr>

        <?php
            while( $query->have_posts() ): $query->the_post();
                $resident_name_terms = get_the_terms( $post->ID, 'resident_name' );
        ?>

        <tr>
            <td class="trunc-name"><?php foreach ($resident_name_terms as $object) { echo $object->name; } ?></td>
        </tr>
        <?php endwhile; ?>
    </table>
endif;

一如既往,非常感谢任何帮助!

【问题讨论】:

  • 什么时候执行截断代码?您需要在动态更新列表后执行此操作。
  • 有道理,谢谢!关于我如何做到这一点的任何见解?我尝试将该 JS 放在应用 AJAX 的函数中,但无济于事。
  • 显示你的尝试,我认为它应该可以工作
  • 我刚刚想出将函数包装在ajaxComplete() 中 - 在任何 ajax 运行后触发。如果您想将其放入答案形式中,我很乐意接受它,因为您的评论导致了答案。
  • 这将在每次 AJAX 调用之后运行,这似乎有点矫枉过正。您应该在更新相关元素的调用的success: 函数中运行它。

标签: php jquery ajax loops truncate


【解决方案1】:

创建新元素后,您需要在 success: 函数中运行截断代码。

$.ajax({
    ...
    success: function(response) {
        ... // code that adds the new HTML
        $('.trunc-name').each(function (d, td) {
            $(td).text($(td).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
        });
    }
});

【讨论】:

    猜你喜欢
    • 2014-06-22
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多