esc_js()

转义单引号,双引号,特殊的 HTML 字符, &,和修正行结束符

描述

转义单引号,双引号,特殊的 HTML 字符,< > &,和修正行结束符。

这个函数主要用来转义输出到 JS 中的文本字符串, 它主要用于 inline JS(比如 a 标签的 onclick 属性中)

需要注意的是生成字符串必须在单引号中。

用法

<?php esc_js( $text ) ?>

参数

$text

(string) (必填) 将转义的文本

默认值: None

返回值

(string

转义之后的 js 字符串。

示例

网站前端显示的表单中的输入标记示例,由小部件生成。第一个php段使用esc_attr因为它是输入的html属性,而接下来的php段在内联Javascript中使用esc_js。

<input type=“text” value=“<?php echo esc_attr( $instance[‘input_text’] ); ?>“ id=“subbox” onfocus=“if ( this.value == ‘<?php echo esc_js( $instance[‘input_text’] ); ?>‘) { this.value = ”; }” onblur=“if ( this.value == ” ) { this.value = ‘<?php echo esc_js( $instance[‘input_text’] ); ?>‘; }” name=“email” />

如上所述,如果您不处理 HTML 事件处理程序属性中的转义字符串(json_encode包含字符串分隔引号),则json_encode适用:

var title = <?php echo json_encode( $instance[‘title’] ) ?>;

注意

开发者可以通过 js_escape 这个 filter 接口对返回字符串进行再次过滤。

历史

添加于 版本: 2.8.0

源文件

esc_js() 函数的代码位于 wp-includes/formatting.php

/**
* Escape single quotes, htmlspecialchar ” <> &, and fix line endings.
*
* Escapes text strings for echoing in JS. It is intended to be used for inline JS
* (in a tag attribute, for example onclick=”…”). Note that the strings have to
* be in single quotes. The filter ‘js_escape’ is also applied here.
*
* @since 2.8.0
*
* @param string $text The text to be escaped.
* @return string Escaped text.
*/

function esc_js( $text ) {

$safe_text = wp_check_invalid_utf8( $text );

$safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );

$safe_text = preg_replace( ‘/&#(x)?0*(?(1)27|39);?/i’, “‘”, stripslashes( $safe_text ) );

$safe_text = str_replace( “”, ”, $safe_text );

$safe_text = str_replace( “

“, ‘n’, addslashes( $safe_text ) );

/**

* Filter a string cleaned and escaped for output in JavaScript.
*
* Text passed to esc_js() is stripped of invalid or special characters,
* and properly slashed for output.
*
* @since 2.0.6
*
* @param string $safe_text The text after it has been escaped.
* @param string $text      The text prior to being escaped.
*/

return apply_filters( ‘js_escape’, $safe_text, $text );

}
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索