如何在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.tw/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.com/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.tw/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