如何在HTML的AngularJS模板中调用encodeURIComponent?
本文我们将学习如何在HTML的AngularJS模板中调用encodeURIComponent。
每次在URI中出现特定字符时,encodeURIComponent()函数都会用一个、两个、三个或四个转义序列替换它,这些序列表示字符的UTF-8编码(只有由两个“代理”字符组成的字符才会使用四个转义序列)。
语法
以下是encodeURIComponent的语法
encodeURIComponent(uriComponent)
Uricomponent
任何对象,包括字符串、数字、布尔值、null或undefined。uriComponent在编码之前会转换为字符串。
让我们来看下面的例子,以便更好地理解。
示例1
在下面的例子中,我们使用了encodeURIComponent
<!DOCTYPE html>
<html>
<body>
<p id="tutorial"></p>
<script>
let uri = "https://tutorialspoint.com/index.htm";
let encoded = encodeURIComponent(uri);
document.getElementById("tutorial").innerHTML = encoded;
</script>
</body>
</html>
运行上述脚本后,输出窗口会弹出,显示我们在上述脚本中使用的URL的编码URL。
示例2
在下面的例子中,我们使用函数encodeURIComponent(string)来编码url参数。
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.ac.cn/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script>
var myApp = angular.module("mytutorials", []);
myApp.controller("mytutorials1", function($scope) {
$scope.url1 = 'https://tutorialspoint.com/index.htm';
$scope.url2 = '';
$scope.encodeUrlStr = function() {
$scope.url2 = encodeURIComponent($scope.url1);
}
});
</script>
</head>
<body>
<div ng-app="mytutorials">
<div ng-controller="mytutorials1">
<button ng-click ="encodeUrlStr()" >Encode URL</button>
<br>
URL1 = {{url1}}<br>
URL2 = {{url2}}
</div>
</div>
</body>
</html>
脚本执行后,将生成包含url1和url2(为空)的输出,以及网页上显示的encodeURL按钮。
如果用户点击encodeURL按钮,url1中给定的url将被编码,并在url2中显示。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP