【问题标题】:Highlighting words with Javascript, what am I missing?用Javascript突出显示单词,我错过了什么?
【发布时间】:2015-04-13 23:36:18
【问题描述】:

我一直在使用基本的 javascript/PHP 聊天室。我希望某些单词在聊天流中出现时突出显示。

聊天室的 html 输出如下所示:

<div class="chat-container">
  <div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
  <div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
  <div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
</div>

我找到了一个实际上是我正在寻找的 Javascript 解决方案(请参阅 https://jsfiddle.net/4ny8adpg/2/ 以获取工作示例)。但是当我尝试将它与聊天室一起使用时,它不会突出显示“Chat-Container” div 中的任何文本。

它会不会因为聊天室的内容是 PHP/Javascript 的输出而不是像 jsfiddle 示例中的 HTML 那样工作?或者,也许我遗漏了一些明显的东西。

任何帮助或建议将不胜感激。

编辑(显示代码并提供更多信息):

聊天室其实是一个wordpress插件,由一个PHP文件和一个Javascript文件组成:

Javascript:

var last_update_received = 0;
function chatroom_check_updates() {
    jQuery.post(
        ajaxurl,
        {
            action: 'check_updates',
            chatroom_slug: chatroom_slug,
            last_update_id: last_update_id
        },
        function (response) {
            chats = jQuery.parseJSON( response );
            if ( chats !== null ) {
                for ( i = 0; i < chats.length; i++ ) {
                    if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
                        continue;
                    jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
                    last_update_id = chats[i].id;
                    jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
                }
            }
        }
    );
    setTimeout( "chatroom_check_updates()", 1000 );
}

function chatroom_strip_slashes(str) {
    return (str + '').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
        case '\\':
            return '\\';
        case '0':
            return '\u0000';
        case '':
            return '';
        default:
            return n1;
        }
    });
}

jQuery(document).ready( function() {
    last_update_id = 0;
    chatroom_check_updates();
    jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
        if ( event.charCode == 13 || event.keyCode == 13 ) {
            chatroom_send_message();
            return false;
        }
    });
});

function chatroom_send_message() {
    message = jQuery( 'textarea.chat-text-entry' ).val();
    jQuery( 'textarea.chat-text-entry' ).val('');
    jQuery.post(
        ajaxurl,
        {
            action: 'send_message',
            chatroom_slug: chatroom_slug,
            message: message
        },
        function (response) {
        }
    );

}

PHP:

Class Chatroom {
    function __construct() {
        register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
        register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
        add_action( 'init', array( $this, 'register_post_types' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
        add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
        add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
        add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
        add_filter( 'the_content', array( $this, 'the_content_filter' ) );
    }
    function activation_hook() {
        $this->register_post_types();
        flush_rewrite_rules();
    }
    function deactivation_hook() {
        flush_rewrite_rules();
    }
    function register_post_types() {
        $labels = array(
            'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
            'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
            'add_new' => _x( 'Add New', 'book', 'chatroom' ),
            'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
            'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
            'new_item' => __( 'New Chat Room', 'chatroom' ),
            'all_items' => __( 'All Chat Rooms', 'chatroom' ),
            'view_item' => __( 'View Chat Room', 'chatroom' ),
            'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
            'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
            'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
            'parent_item_colon' => '',
            'menu_name' => __( 'Chat Rooms', 'chatroom' )
        );
        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'show_in_nav_menus' => true,
            'supports' => array( 'title' )
        );
        register_post_type( 'chat-room', $args );
    }
    function enqueue_scripts() {
        global $post;
        if ( $post->post_type != 'chat-room' )
            return;
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
        wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
    }
    function maybe_create_chatroom_log_file( $post_id, $post ) {
        if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
            return;
        $upload_dir = wp_upload_dir();
        $log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
        if ( file_exists( $log_filename ) )
            return;
        wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
        $handle = fopen( $log_filename, 'w' );
        fwrite( $handle, json_encode( array() ) );
        // TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
    }
    function define_javascript_variables() {
        global $post;
        if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
            return; ?>
        <script>
        var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
        var chatroom_slug = '<?echo $post->post_name; ?>';
        </script>
        <?php
    }
    function ajax_check_updates_handler() {
        $upload_dir = wp_upload_dir();
        $log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
        $contents = $this->parse_messages_log_file( $log_filename );
        $messages = json_decode( $contents );
        foreach ( $messages as $key => $message ) {
            if ( $message->id <= $_POST['last_update_id'] )
                unset( $messages[$key] );
        }
        $messages = array_values( $messages );
        echo json_encode( $messages );
        die;
    }
    /**
     * AJAX server-side handler for sending a message.
     *
     * Stores the message in a recent messages file.
     *
     * Clears out cache of any messages older than 10 seconds.
     */
    function ajax_send_message_handler() {
        $current_user = wp_get_current_user();
        $this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
        die;
    }
    function save_message( $chatroom_slug, $user_id, $content ) {
        $user = get_userdata( $user_id );
        if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
            // Set random color for each user
            $red = rand( 0, 16 );
            $green = 16 - $red;
            $blue = rand( 0, 16 );
            $user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
            update_user_meta( $user_id, 'user_color', $user_text_color );
        }
        $content = esc_attr( $content );
        // Save the message in recent messages file
        $log_filename = $this->get_log_filename( $chatroom_slug );
        $contents = $this->parse_messages_log_file( $log_filename );
        $messages = json_decode( $contents );
        $last_message_id = 0; // Helps determine the new message's ID
        foreach ( $messages as $key => $message ) {
            if ( time() - $message->time > 10 ) {
                $last_message_id = $message->id;
                unset( $messages[$key] );
            }
            else {
                break;
            }
        }
        $messages = array_values( $messages );
        if ( ! empty( $messages ) )
            $last_message_id = end( $messages )->id;
        $new_message_id = $last_message_id + 1;
        $messages[] = array(
            'id' => $new_message_id,
            'time' => time(),
            'sender' => $user_id,
            'contents' => $content,
            'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
        );
        $this->write_log_file( $log_filename, json_encode( $messages ) );
        // Save the message in the daily log
        $log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
        $contents = $this->parse_messages_log_file( $log_filename );
        $messages = json_decode( $contents );
        $messages[] = array(
            'id' => $new_message_id,
            'time' => time(),
            'sender' => $user_id,
            'contents' => $content,
            'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
        );
        $this->write_log_file( $log_filename, json_encode( $messages ) );
    }
    function write_log_file( $log_filename, $content ) {
        $handle = fopen( $log_filename, 'w' );
        fwrite( $handle, $content );
    }
    function get_log_filename( $chatroom_slug, $date = 'recent' ) {
        $upload_dir = wp_upload_dir();
        $log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
        return $log_filename;
    }
    function parse_messages_log_file( $log_filename ) {
        $upload_dir = wp_upload_dir();
        $handle = fopen( $log_filename, 'r' );
        $contents = fread( $handle, filesize( $log_filename ) );
        fclose( $handle );
        return $contents;
    }
    function the_content_filter( $content ) {
        global $post;
        if ( $post->post_type != 'chat-room' )
            return $content;
        if ( ! is_user_logged_in() )  {
            ?>You need to be logged in to participate in the chatroom.<?php
            return;
        }
        ?>
        <div class="chat-container">
        </div>
        <textarea class="chat-text-entry"></textarea>
        <?php
        return '';
    }
}
$chatroom = new Chatroom();

JSON 示例:

[{"id":129,"time":1428340673,"sender":1,"contents":"What is your favourite animal?","html":"<div class=\"chat chat-message-129\"><strong style=\"color: #840;\">User 1<\/strong>: What is your favourite animal?<\/div>"},
{"id":130,"time":1428351683,"sender":2,"contents":"I vote for #dog.","html":"<div class=\"chat chat-message-130\"><strong style=\"color: #840;\">User 2<\/strong>: I vote for #dog.<\/div>"},
{"id":131,"time":1428352376,"sender":3,"contents":"I have a #cat!","html":"<div class=\"chat chat-message-131\"><strong style=\"color: #840;\">User 3<\/strong>: I have a #cat!<\/div>"}]

【问题讨论】:

  • 在页面添加聊天内容的时候调用代码好吗???当您动态添加内容时,小提琴中的代码不会神奇地更新页面。
  • 是的,您可能遗漏了一些明显的东西。由 PHP/javascript(可能是 AJAX)提供的文本可以在客户端以任何您在将其附加到 DOM 之前或之后选择的方式进行处理。
  • 我想问题是你什么时候想突出主题标签?聊天文本是通过 PHP 传递还是在使用 JavaScript 或 JQuery 出现在浏览器中之后?
  • 是的,如果它是通过 AJAX 调用返回的,请从 success() 回调中调用该代码
  • 我认为真正的问题是@Drakes 问题!你有什么,所以我们可以讨论真正的解决方案,而不仅仅是假设性地评论那里有什么!

标签: javascript php jquery html css


【解决方案1】:

如果您希望在 AJAX 调用返回后运行突出显示代码(当有新的 HTML 片段时),请尝试以下方式:

$.ajax({
    ...
    success : function(data) {              
       ...    

       $('.chat').each(function(){
          var hashtag = $(this).text()
          .replace(/#dog/g, "<span class='dog'>#DOG</span>")
          .replace(/#cat/g, "<span class='cat'>#CAT</span>");
          $(this).html(hashtag);
       });   

    },
    ...
});

在您的情况下,在填充所有聊天片段后调用突出显示代码:

...
function (response) {
    chats = jQuery.parseJSON( response );
    if ( chats !== null ) {
        for ( i = 0; i < chats.length; i++ ) {
            if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
                continue;
            jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
            last_update_id = chats[i].id;
            jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
        }

        // Call highlighting code here
    }
}
...

PS 您可以通过将选择器 jQuery('div.chat-container') 缓存为变量来节省时间,这样 jQuery 就不必每次都搜索您的 HTML。

【讨论】:

  • 谢谢@Drakes,我已按照说明添加了代码,但在控制台中收到错误消息:如果我按照说明将 JS 代码从我的 JSfiddle 添加到该位置,我会收到:“未捕获的类型错误:未定义不是函数”。如果我从答案的第一部分添加 JS 代码( $.ajax({ ) 我收到:“Uncaught TypeError: Cannot read property 'ajax' of undefined”。我的菜鸟没有界限,我还在做错什么? :P
  • 我会尽快为您调查。目前正在工作。我相信我们可以解决这个问题。你能更新你的小提琴并发布新链接吗?
  • 说真的,非常感谢任何帮助。 jsfiddle 的链接:jsfiddle.net/4ny8adpg/3.
  • 嗨@TrudgeMoody,我在这里修改了你的演示:jsbin.com/juveyaqupo/2 请把它倒过来看看我的 cmets 让你跟随。希望对您有所帮助。
  • 嗨@Drakes,许多人为延迟回复道歉!我现在只是在尝试代码,并会立即报告。
猜你喜欢
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多