From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../zh-cn/web/api/domtokenlist/replace/index.html | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 files/zh-cn/web/api/domtokenlist/replace/index.html (limited to 'files/zh-cn/web/api/domtokenlist/replace/index.html') diff --git a/files/zh-cn/web/api/domtokenlist/replace/index.html b/files/zh-cn/web/api/domtokenlist/replace/index.html new file mode 100644 index 0000000000..53652d2c10 --- /dev/null +++ b/files/zh-cn/web/api/domtokenlist/replace/index.html @@ -0,0 +1,82 @@ +--- +title: DOMTokenList.replace() +slug: Web/API/DOMTokenList/replace +translation_of: Web/API/DOMTokenList/replace +--- +

{{APIRef("DOM")}}

+ +

{{domxref("DOMTokenList")}}接口的 replace() 方法可以将列表中一个已存在的token替换为一个新token。如果第一个参数token在列表中不存在, replace() 立刻返回false ,而不会将新token字符串添加到列表中。

+ +

语法

+ +
tokenList.replace(oldToken, newToken);
+ +

参数

+ +
+
oldToken
+
{{domxref("DOMString")}}类型,想要替换掉的字符串。
+
newToken
+
{{domxref("DOMString")}}类型,表示要将oldToken字符串替换成的字符串。
+
+ +

返回值

+ +

boolean类型, 如果oldToken被成功替换,返回 true ,否则返回false

+ +
+

Note: In older browsers, replace() returns void.

+
+ +

Examples

+ +

在下面的例子中,我们使用{{domxref("Element.classList")}}方法,将设置在{{htmlelement("span")}} 元素上的class列表检索为DOMTokenList 类型。接着我们替换一个字符串, 并且将新列表写入到 <span> 的内容{{domxref("Node.textContent")}}中。

+ +

首先,HTML代码如下:

+ +
<span class="a b c"></span>
+ +

然后是JavaScript:

+ +
let span = document.querySelector("span");
+let classes = span.classList;
+
+let result = classes.replace("c", "z");
+console.log(result);
+
+if (result) {
+  span.textContent = classes;
+} else {
+  span.textContent = 'token not replaced successfully';
+}
+ +

输出如下:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-domtokenlist-replace','replace()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.DOMTokenList.replace")}}

+
-- cgit v1.2.3-54-g00ecf