在Javascript中突出显示单词 - 为什么在页面完全加载后它们不会保持突出显示? [英] Highlighting words in Javascript - Why won't they stay highlighted after the page fully loads?
问题描述
所以这是一个关于@Drakes先前在这个问题上做过的杰出工作的问题:用Javascript突出显示单词,我错过了什么?。
解决方案是通过查找#cat或#dog并用
<$替换它们来突出显示单词p $ p> < span class ='cat'>#CAT< / span>
或
< span class ='dog'>#DOG< / span>
然后我们可以用CSS控制span标签的背景颜色。
这个效果很好,但背景颜色在消失之前只保留一小段时间。仔细一看,似乎span标签被正确应用,然后突然再次被移除。
以下是您需要查看的实际示例,以及日志详细地运行任何测试和查看聊天。
[已移除,不再存在]
以下是上一个问题中的更新代码目前正在运行的实例。
再次感谢您的进一步帮助。请让我知道,如果您需要任何额外的信息!
Javascript:
//注意:我需要定义这些变量以使演示工作
var ajaxurl =http://ip.jsontest.com/;
var chatroom_slug =1;
var last_update_id =1;
var last_update_received = 0;
函数chatroom_check_updates(){
jQuery.post(
ajaxurl,
{
action:'check_updates',
chatroom_slug:chatroom_slug,
last_update_id:last_update_id
},
函数(响应){
//注意:响应不好,会抛出异常,而不是NULL
chats = null;
try {
chats = jQuery.parseJSON(response);
} catch(e){}
$ b $ // //注意: ,我不知道你的URL,所以我只是在
之下注释掉了(1 || chats!== null){
for(i = 0; i< chats.length; i ++){
if(jQuery('div.chat-container div.chat-message - '+ chats [i] .id).length)
continue;
jQuery('div。聊天容器')。html(jQuery('div.chat-container')。html()+ chatroom_strip_sl灰烬(聊天[i] .html));
last_update_id =聊天[i] .id; $ {$ b $ j jQuery('div.chat-container')。animate {{scrollTop:jQuery('div.chat-container')[0] .scrollHeight - jQuery('div.chat-container')。height() },100);
$ b $ jQuery('。chat')。each(function(){
var hashtag = jQuery(this).text()
.replace(/ #dog / g< span class ='dog'>#DOG< / span>)
.replace(/#cat / g,< span class ='cat'>#CAT< ; / span>);
jQuery(this).html(hashtag);
});
$ b .error(function(xhr,status,error){
alert(xhr.responseText);
});
//我评论这一点只是为了测试。
setTimeout(chatroom_check_updates,1000);
}
函数chatroom_strip_slashes(str){
return(str +'').replace(/ \\(。?)/ g,function(s,n1 ){
switch(n1){
case'\\\':
return'\\';
case'0':
return' \\\ ';
case'':
return'';
default:
return n1;
}
});
jQuery(document).ready(function(){
last_update_id = 0;
chatroom_check_updates();
jQuery('textarea.chat ();
if(event.charCode == 13 || event.keyCode == 13){
chatroom_send_message();
return false ;
}
});
});
函数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
},
函数(响应){
}
);
$ b
PHP:
<?php
/ *
插件名称:聊天室
插件URI:http://webdevstudios.com/support/ wordpress-plugins /
描述:Chat for WordPress
作者:WebDevStudios.com
版本:0.1.2
作者URI:http://webdevstudios.com/
许可证:GPLv2或更高版本
* /
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'));
函数activation_hook(){
$ this-> register_post_types();
flush_rewrite_rules();
}
函数deactivation_hook(){
flush_rewrite_rules();
函数register_post_types(){
$ labels = array($ b $'name'=> _x('Chat Rooms','post type general name' ,'chatroom'),
'singular_name'=> _x('聊天室','发帖类型单数名称','聊天室'),
'add_new'=> _x('Add New ','book','chatroom'),
'add_new_item'=> __('Add New Chat Room','chatroom'),
'edit_item'=> __('Edit Chat ('聊天室','聊天室'),
'all_items'=> __('所有聊天室','所有聊天室','聊天室'),
'new_item'=> __ chatroom'),
'view_item'=> __('查看聊天室','chatroom'),
'search_items'=> __('搜索聊天室','聊天室'
'not_found'=> __('找不到聊天室','聊天室'),
'not_found_in_trash'=> __('在垃圾箱中找不到聊天室','聊天室'),
'parent_item_colon'=>'',
'menu_name'=> __('聊天室','聊天室')
);
$ args = array(
'labels'=> $ labels,
'public'=> true,
'public_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 '=>数组('title')
);
register_post_type('chat-room',$ args);
}
函数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__));
}
函数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()));
//如果用户无法创建文件,并建议将FTP信誉放入wp-config
函数define_javascript_variables(){
全球$ 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
}
函数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);
死亡;
}
/ **
*用于发送消息的AJAX服务器端处理程序。
*
*将消息存储在最近的消息文件中。
*
*清除超过10秒的任何消息的缓存。
* /
函数ajax_send_message_handler(){
$ current_user = wp_get_current_user();
$ this-> save_message($ _POST ['chatroom_slug'],$ current_user-> id,$ _POST ['message']);
死亡;
函数save_message($ chatroom_slug,$ user_id,$ content){
$ user = get_userdata($ user_id);
if(!$ user_text_color = get_user_meta($ user_id,'user_color',true)){
//为每个用户设置随机颜色
$ 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);
//将消息保存在最近的消息文件中
$ log_filename = $ this-> get_log_filename($ chatroom_slug);
$ contents = $ this-> parse_messages_log_file($ log_filename);
$ messages = json_decode($ contents);
$ last_message_id = 0; //帮助确定新消息的ID
foreach($ message为$ key => $ message){
if(time() - $ message-> time> 100){
$ 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 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));
//将消息保存在日志中
$ 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 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));
函数write_log_file($ log_filename,$ content){
$ handle = fopen($ log_filename,'w');
fwrite($ handle,$ content);
$ b函数get_log_filename($ chatroom_slug,$ date ='recent'){
$ upload_dir = wp_upload_dir();
$ log_filename = $ upload_dir ['basedir']。 '/ chatter /'。 $ chatroom_slug。 ' - '。 $日期;
返回$ log_filename;
函数parse_messages_log_file($ log_filename){
$ upload_dir = wp_upload_dir();
$ handle = fopen($ log_filename,'r');
$ contents = fread($ handle,filesize($ log_filename));
fclose($ handle);
返回$ contents;
}
函数the_content_filter($ content){
global $ post;
if($ post-> post_type!='chat-room')
return $ content;
if(!is_user_logged_in()){
?>您需要登录才能参加聊天室。<?php
return;
}
?>
< div class =chat-container>
< / div>
<?php
return'';
}
}
$ chatroom = new Chatroom();
HTML输出示例:
< div class =chat-container>
< div class =chat chat-message-111>< strong style =color:#840;>用户1< / strong> ;:您最喜欢的动物是什么?< / div> ;
< div class =chat chat-message-112>< strong style =color:#840;> User 2< / strong> ;:我投给了#dog。 < / DIV>
< div class =chat chat-message-113>< strong style =color:#840;> User 3< / strong>:我有#cat!< / div> ;
< / div>
因为即使存在不匹配。所以.text()去除了HTML,并且它不会找到狗或猫,只是放入文本。
var hashtag = / jQuery(this).text()
.replace(/#dog / g,< span class ='dog'>#DOG< / span>)
.replace(/ cat / g,< span class ='cat'>#CAT< / span>);
jQuery(this).html(hashtag);
由于您将#dog替换为#DOG,因此搜索不区分大小写, p>
要么不区分大小写
/#dog / gi
或者只有在发生更改时才替换文字。
var orgText = jQuery(this).text();
var hashtag = orgText
.replace(/#dog / g,< span class ='dog'>#DOG< / span>)
.replace(/#cat / g,< span class ='cat'>#CAT< / span>);
if(orgText!== hashtag){
jQuery(this).html(hashtag);
}
注意:你现在写的方式,你会被吹走用户格式化,因为您正在阅读文本。
So this is a question following on from the awesome work @Drakes has done on this question previously: Highlighting words with Javascript, what am I missing?.
The solution is to highlight words by finding "#cat" or "#dog" and replacing them with
<span class='cat'>#CAT</span>
or
<span class='dog'>#DOG</span>
Then we can control the background colour of the span tag with CSS.
This works perfectly, however the background colour only remains for a brief moment before disappearing. Upon a closer look, it seems the span tags are applied correctly and then removed again suddenly.
Here is the actual working example for you to have a look at, plus log in details to run any tests and to view the chat.
[Removed, no longer exists]
Below is the updated code from the previous question that is currently running on the working example.
Once again, any further help is hugely appreciated. Please let me know if you require any additional information!
Javascript:
// NOTE: I needed to define these variables to make the demo work
var ajaxurl = "http://ip.jsontest.com/";
var chatroom_slug = "1";
var last_update_id = "1";
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) {
// NOTE: the response is bad, an exception will be thrown, not NULL
chats = null;
try {
chats = jQuery.parseJSON( response );
} catch(e) {}
// NOTE: In this test, I don't know your URL, so I just commented out the bit below
if (1 || 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);
}
jQuery('.chat').each(function(){
var hashtag = jQuery(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
jQuery(this).html(hashtag);
});
}
}
)
.error(function(xhr, status, error){
alert(xhr.responseText);
});
// I commented this out just for testing.
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:
<?php
/*
Plugin Name: Chat Room
Plugin URI: http://webdevstudios.com/support/wordpress-plugins/
Description: Chat Room for WordPress
Author: WebDevStudios.com
Version: 0.1.2
Author URI: http://webdevstudios.com/
License: GPLv2 or later
*/
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 > 100 ) {
$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 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 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();
Example HTML output:
<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>
Because you are replacing all the text even if there is not a match. So .text() strips the HTML and than it does not find dog or cat and just puts the text in.
var hashtag = jQuery(this).text()
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
jQuery(this).html(hashtag);
since you replace #dog with #DOG it will not match since the search is not case insensitive
either make it case insensitive
/#dog/gi
or only replace the text if there is a change made.
var orgText = jQuery(this).text();
var hashtag = orgText
.replace(/#dog/g, "<span class='dog'>#DOG</span>")
.replace(/#cat/g, "<span class='cat'>#CAT</span>");
if(orgText!==hashtag) {
jQuery(this).html(hashtag);
}
Note: the way you have it currently written, you are going to blow away the User formatting since you are reading the text.
这篇关于在Javascript中突出显示单词 - 为什么在页面完全加载后它们不会保持突出显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!