diff --git a/files/zh-cn/web/api/htmlformelement/formdata_event/index.md b/files/zh-cn/web/api/htmlformelement/formdata_event/index.md index 1c8423519e6536..90f227967950db 100644 --- a/files/zh-cn/web/api/htmlformelement/formdata_event/index.md +++ b/files/zh-cn/web/api/htmlformelement/formdata_event/index.md @@ -22,11 +22,11 @@ target.onformdata = functionRef; ```js // grab reference to form -const formElem = document.querySelector('form'); +const formElem = document.querySelector("form"); // submit handler -formElem.addEventListener('submit', (e) => { +formElem.addEventListener("submit", (e) => { // on form submission, prevent default e.preventDefault(); @@ -37,7 +37,7 @@ formElem.addEventListener('submit', (e) => { // formdata handler to retrieve data formElem.onformdata = (e) => { - console.log('formdata fired'); + console.log("formdata fired"); // Get the form data from the event object let data = e.formData; diff --git a/files/zh-cn/web/api/htmlformelement/index.md b/files/zh-cn/web/api/htmlformelement/index.md index 614bad4dbd8185..514edf5d3e6250 100644 --- a/files/zh-cn/web/api/htmlformelement/index.md +++ b/files/zh-cn/web/api/htmlformelement/index.md @@ -64,7 +64,7 @@ document.body.appendChild(f); // Add action and method attributes f.action = "/cgi-bin/some.cgi"; -f.method = "POST" +f.method = "POST"; // Call the form's submit method f.submit(); @@ -80,16 +80,34 @@ In addition, the following complete HTML document shows how to extract informati // Get a reference using the forms collection var f = document.forms["formA"]; - info = "f.elements: " + f.elements + "\n" - + "f.length: " + f.length + "\n" - + "f.name: " + f.name + "\n" - + "f.acceptCharset: " + f.acceptCharset + "\n" - + "f.action: " + f.action + "\n" - + "f.enctype: " + f.enctype + "\n" - + "f.encoding: " + f.encoding + "\n" - + "f.method: " + f.method + "\n" - + "f.target: " + f.target; - document.forms["formA"].elements['tex'].value = info; + info = + "f.elements: " + + f.elements + + "\n" + + "f.length: " + + f.length + + "\n" + + "f.name: " + + f.name + + "\n" + + "f.acceptCharset: " + + f.acceptCharset + + "\n" + + "f.action: " + + f.action + + "\n" + + "f.enctype: " + + f.enctype + + "\n" + + "f.encoding: " + + f.encoding + + "\n" + + "f.method: " + + f.method + + "\n" + + "f.target: " + + f.target; + document.forms["formA"].elements["tex"].value = info; } // A reference to the form is passed from the @@ -97,27 +115,24 @@ In addition, the following complete HTML document shows how to extract informati function setFormInfo(f) { f.method = "GET"; f.action = "/cgi-bin/evil_executable.cgi"; - f.name = "totally_new"; + f.name = "totally_new"; } -

Form example

- -
-

Click "Info" to see information about the form. - Click set to change settings, then info again - to see their effect

-

- - - -
- -

+

Form example

+ + +

+ Click "Info" to see information about the form. Click set to change + settings, then info again to see their effect +

+

+ + + +
+ +

``` @@ -126,45 +141,77 @@ The following example shows how to submit a form in a [popup window](/zh-CN/docs ```html - - -MDN Example - - - - - - -
-

First name:
- Last name:
- Password:
- Male Female

-

I have a bike
- I have a car

-

-
- - + + + MDN Example + + + + +
+

+ First name:
+ Last name:
+ Password:
+ Male + Female +

+

+ I have a bike
+ I have a car +

+

+
+ ``` diff --git a/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md b/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md index 313db0bd1dc33b..3761a89a5ca465 100644 --- a/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md +++ b/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md @@ -20,13 +20,21 @@ HTMLFormElement.reportValidity() ## Example ```js -document.forms['myform'].addEventListener('invalid', function() { - // Optional response here -}, false); - -document.forms['myform'].addEventListener('submit', function() { - document.forms['myform'].reportValidity(); -}, false); +document.forms["myform"].addEventListener( + "invalid", + function () { + // Optional response here + }, + false, +); + +document.forms["myform"].addEventListener( + "submit", + function () { + document.forms["myform"].reportValidity(); + }, + false, +); ``` ## Specifications diff --git a/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md b/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md index 3efffcdb7f7094..0ba002bbed7a5c 100644 --- a/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md +++ b/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md @@ -10,8 +10,8 @@ slug: Web/API/HTMLFormElement/requestSubmit ## 语法 ```js -requestSubmit() -requestSubmit(submitter) +requestSubmit(); +requestSubmit(submitter); ``` ### 参数 diff --git a/files/zh-cn/web/api/htmlformelement/reset_event/index.md b/files/zh-cn/web/api/htmlformelement/reset_event/index.md index 6be4b65da39e97..991d1c9e27beb1 100644 --- a/files/zh-cn/web/api/htmlformelement/reset_event/index.md +++ b/files/zh-cn/web/api/htmlformelement/reset_event/index.md @@ -22,12 +22,12 @@ slug: Web/API/HTMLFormElement/reset_event ## 属性 -| Property | Type | Description | -| ------------------------------------- | ------------------------------------ | ---------------------------------- | +| Property | Type | Description | +| ------------------------------- | -------------------------- | ---------------------------------- | | `target` {{readonlyInline}} | {{domxref("EventTarget")}} | 事件的目标(DOM 树最顶端的元素)。 | -| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 事件的类型。 | -| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 是否指定事件冒泡。 | -| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否可以被取消。 | +| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 事件的类型。 | +| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 是否指定事件冒泡。 | +| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否可以被取消。 | ## 规范 diff --git a/files/zh-cn/web/api/htmlformelement/submit/index.md b/files/zh-cn/web/api/htmlformelement/submit/index.md index a6cba238d2868b..afb4282986c6cc 100644 --- a/files/zh-cn/web/api/htmlformelement/submit/index.md +++ b/files/zh-cn/web/api/htmlformelement/submit/index.md @@ -20,8 +20,8 @@ slug: Web/API/HTMLFormElement/submit ## 语法 - ```js -submit() +```js +submit(); ``` ### 参数 diff --git a/files/zh-cn/web/api/htmlformelement/submit_event/index.md b/files/zh-cn/web/api/htmlformelement/submit_event/index.md index e0e6d718d457c9..817628700a84c6 100644 --- a/files/zh-cn/web/api/htmlformelement/submit_event/index.md +++ b/files/zh-cn/web/api/htmlformelement/submit_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLFormElement: submit event' +title: "HTMLFormElement: submit event" slug: Web/API/HTMLFormElement/submit_event --- @@ -42,8 +42,8 @@ slug: Web/API/HTMLFormElement/submit_event ```html
- -

+ +

@@ -57,9 +57,9 @@ function logSubmit(event) { event.preventDefault(); } -const form = document.getElementById('form'); -const log = document.getElementById('log'); -form.addEventListener('submit', logSubmit); +const form = document.getElementById("form"); +const log = document.getElementById("log"); +form.addEventListener("submit", logSubmit); ``` ### 结果 diff --git a/files/zh-cn/web/api/htmlimageelement/decode/index.md b/files/zh-cn/web/api/htmlimageelement/decode/index.md index d02ac8790ea735..11a3bd70013bc3 100644 --- a/files/zh-cn/web/api/htmlimageelement/decode/index.md +++ b/files/zh-cn/web/api/htmlimageelement/decode/index.md @@ -35,14 +35,15 @@ var promise = HTMLImageElement.decode(); ```js const img = new Image(); -img.src = 'nebula.jpg'; -img.decode() -.then(() => { - document.body.appendChild(img); -}) -.catch((encodingError) => { - // Do something with the error. -}) +img.src = "nebula.jpg"; +img + .decode() + .then(() => { + document.body.appendChild(img); + }) + .catch((encodingError) => { + // Do something with the error. + }); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlimageelement/decoding/index.md b/files/zh-cn/web/api/htmlimageelement/decoding/index.md index 17566534e97ef1..05a917b593f09b 100644 --- a/files/zh-cn/web/api/htmlimageelement/decoding/index.md +++ b/files/zh-cn/web/api/htmlimageelement/decoding/index.md @@ -28,8 +28,8 @@ imgElem.decoding = refStr; ```js var img = new Image(); -img.decoding = 'sync'; -img.src = 'img/logo.png'; +img.decoding = "sync"; +img.src = "img/logo.png"; ``` ## Specifications diff --git a/files/zh-cn/web/api/htmlimageelement/image/index.md b/files/zh-cn/web/api/htmlimageelement/image/index.md index 37abab4fb9deaa..146be0f41bd1d0 100644 --- a/files/zh-cn/web/api/htmlimageelement/image/index.md +++ b/files/zh-cn/web/api/htmlimageelement/image/index.md @@ -26,14 +26,14 @@ Image(width, height) ```js var myImage = new Image(100, 200); -myImage.src = 'picture.jpg'; +myImage.src = "picture.jpg"; document.body.appendChild(myImage); ``` 上面的代码相当于在 {{htmlelement("body")}}中定义了下面的 HTML: ```html - + ``` > **备注:** 无论构造函数中指定的大小是多少,都会加载整个位图。如果在构造时指定了尺寸信息,那么将会反应在实例的 {{domxref("HTMLImageElement.width")}} 和 {{domxref("HTMLImageElement.height")}} 属性上。图像自身的 CSS 像素值将会反应在{{domxref("HTMLImageElement.naturalWidth")}} 和 {{domxref("HTMLImageElement.naturalHeight")}}属性。如果没有指定值,那么两个属性的值相同 diff --git a/files/zh-cn/web/api/htmlimageelement/index.md b/files/zh-cn/web/api/htmlimageelement/index.md index 47ce75384ed482..c9b88276dd3339 100644 --- a/files/zh-cn/web/api/htmlimageelement/index.md +++ b/files/zh-cn/web/api/htmlimageelement/index.md @@ -92,13 +92,13 @@ If an error occurs while trying to load or render the image, and an [`onerror`]( ```js var img1 = new Image(); // Image 构造器 -img1.src = 'image1.png'; -img1.alt = 'alt'; +img1.src = "image1.png"; +img1.alt = "alt"; document.body.appendChild(img1); -var img2 = document.createElement('img'); // 使用 DOM HTMLImageElement -img2.src = 'image2.jpg'; -img2.alt = 'alt text'; +var img2 = document.createElement("img"); // 使用 DOM HTMLImageElement +img2.src = "image2.jpg"; +img2.alt = "alt text"; document.body.appendChild(img2); // 使用文档中的第一个 img diff --git a/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md b/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md index 6a766dfd522d46..0342d4f03f4691 100644 --- a/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md +++ b/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md @@ -25,10 +25,11 @@ slug: Web/API/HTMLImageElement/naturalHeight ```html
- -
-
+
+
``` HTML 具有一个 400x398 像素的图像,该图像放置在一个 {{HTMLElement("div")}} 元素中。 @@ -58,11 +59,12 @@ HTML 具有一个 400x398 像素的图像,该图像放置在一个 {{HTMLEleme let output = document.querySelector(".output"); let image = document.querySelector("img"); -window.addEventListener("load", event => { - output.innerHTML += `Natural size: ${image.naturalWidth} x ` + - `${image.naturalHeight} pixels
`; - output.innerHTML += `Displayed size: ${image.width} x ` + - `${image.height} pixels`; +window.addEventListener("load", (event) => { + output.innerHTML += + `Natural size: ${image.naturalWidth} x ` + + `${image.naturalHeight} pixels
`; + output.innerHTML += + `Displayed size: ${image.width} x ` + `${image.height} pixels`; }); ``` diff --git a/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md index beda5b84318fd7..8140876b209843 100644 --- a/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md +++ b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md @@ -24,10 +24,10 @@ imgElt.referrerPolicy = refStr; ```js var img = new Image(); -img.src = 'img/logo.png'; -img.referrerPolicy = 'origin'; +img.src = "img/logo.png"; +img.referrerPolicy = "origin"; -var div = document.getElementById('divAround'); +var div = document.getElementById("divAround"); div.appendChild(img); // Fetch the image using the origin as the referrer ``` diff --git a/files/zh-cn/web/api/htmlimageelement/srcset/index.md b/files/zh-cn/web/api/htmlimageelement/srcset/index.md index 99d8dd2b95cf19..a87a5cc6675d70 100644 --- a/files/zh-cn/web/api/htmlimageelement/srcset/index.md +++ b/files/zh-cn/web/api/htmlimageelement/srcset/index.md @@ -57,9 +57,13 @@ let srcset = htmlImageElement.srcset; ```html
- Clock + Clock
``` diff --git a/files/zh-cn/web/api/htmlinputelement/index.md b/files/zh-cn/web/api/htmlinputelement/index.md index 4055ed41d9ec7d..ab00b81e703022 100644 --- a/files/zh-cn/web/api/htmlinputelement/index.md +++ b/files/zh-cn/web/api/htmlinputelement/index.md @@ -11,55 +11,55 @@ slug: Web/API/HTMLInputElement ## 属性 -| `form` {{readonlyInline}} | _`{{domxref("HTMLFormElement")}} object:`_ 返回一个父表单元素的引用。 | -| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `formAction` | _`string`:_ **返回/ 设置** 元素的 [`formaction`](/zh-CN/docs/Web/HTML/Element/input#formaction) 属性,包含处理元素提交信息程序的 URI. 这会重写父表单的 [`action`](/zh-CN/docs/Web/HTML/Element/form#action) 属性。 | -| `formEncType` | _`string`:_ **返回/ 设置** 元素的 [`formenctype`](/zh-CN/docs/Web/HTML/Element/input#formenctype) 属性,包含将表单提交到服务器的内容类型。这会重写父表单的 [`enctype`](/zh-CN/docs/Web/HTML/Element/form#enctype) 属性。 | -| `formMethod` | _`string`:_ **返回/ 设置** 元素的 [`formmethod`](/zh-CN/docs/Web/HTML/Element/input#formmethod) 属性,包含浏览器用于提交表单的 HTTP 方法。这会重写父表单的 [`method`](/zh-CN/docs/Web/HTML/Element/form#method) 属性。 | -| `formNoValidate` | _`boolean`:_ **返回/ 设置** 元素的 [`formnovalidate`](/zh-CN/docs/Web/HTML/Element/input#formnovalidate) 属性,表示在表单提交时不对其进行验证。这会重写父表单的 [`novalidate`](/zh-CN/docs/Web/HTML/Element/form#novalidate) 属性。 | -| `formTarget` | _`string`:_ **返回/ 设置** 元素的 [`formtarget`](/zh-CN/docs/Web/HTML/Element/input#formtarget) 属性,包含一个名称或关键字,表示在提交表单后接收响应的显示位置。这会重写父表单的 [`target`](/zh-CN/docs/Web/HTML/Element/form#target) 属性。 | +| `form` {{readonlyInline}} | _`{{domxref("HTMLFormElement")}} object:`_ 返回一个父表单元素的引用。 | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `formAction` | _`string`:_ **返回/ 设置** 元素的 [`formaction`](/zh-CN/docs/Web/HTML/Element/input#formaction) 属性,包含处理元素提交信息程序的 URI. 这会重写父表单的 [`action`](/zh-CN/docs/Web/HTML/Element/form#action) 属性。 | +| `formEncType` | _`string`:_ **返回/ 设置** 元素的 [`formenctype`](/zh-CN/docs/Web/HTML/Element/input#formenctype) 属性,包含将表单提交到服务器的内容类型。这会重写父表单的 [`enctype`](/zh-CN/docs/Web/HTML/Element/form#enctype) 属性。 | +| `formMethod` | _`string`:_ **返回/ 设置** 元素的 [`formmethod`](/zh-CN/docs/Web/HTML/Element/input#formmethod) 属性,包含浏览器用于提交表单的 HTTP 方法。这会重写父表单的 [`method`](/zh-CN/docs/Web/HTML/Element/form#method) 属性。 | +| `formNoValidate` | _`boolean`:_ **返回/ 设置** 元素的 [`formnovalidate`](/zh-CN/docs/Web/HTML/Element/input#formnovalidate) 属性,表示在表单提交时不对其进行验证。这会重写父表单的 [`novalidate`](/zh-CN/docs/Web/HTML/Element/form#novalidate) 属性。 | +| `formTarget` | _`string`:_ **返回/ 设置** 元素的 [`formtarget`](/zh-CN/docs/Web/HTML/Element/input#formtarget) 属性,包含一个名称或关键字,表示在提交表单后接收响应的显示位置。这会重写父表单的 [`target`](/zh-CN/docs/Web/HTML/Element/form#target) 属性。 | -| `name` | _`string`:_ **返回/ 设置** 元素的 [`name`](/zh-CN/docs/Web/HTML/Element/input#name) 属性,包含其名称。 | -| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `type` | `string:` **返回/ 设置** 元素的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性,包含其显示类型。查看 {{ HTMLElement("input") }} 的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性可用值。 | -| `disabled` | _`boolean`:_ **返回/ 设置** 元素的 [`disabled`](/zh-CN/docs/Web/HTML/Element/input#disabled) 属性,表示是否禁用 {{ HTMLElement("input") }}. 该元素的值将不会被提交。也可以查看 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) | -| `autofocus` | `boolean:` **返回/ 设置** 元素的 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性,指定的 {{ HTMLElement("input") }} 在页面加载时应当具有输入焦点,例如通过键入不同的控件。在文档中只有一个表单元素可以拥有 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性。如果 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性被设置为 `hidden` 则无效 (即不可为隐藏控件设置自动焦点). | -| `required` | _`boolean`:_ **返回/ 设置** 元素的 [`required`](/zh-CN/docs/Web/HTML/Element/input#required) 属性,表示用户必填项。 | -| `value` | `string:` **返回/ 设置** 当前控件的值。**提示:** 如果用户输入与预期不同,可能会返回空。 | -| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity state that this element is in. | -| `validationMessage` {{readonlyInline}} | `string:` **Returns** a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ([`willvalidate`](/zh-CN/docs/Web/HTML/Element/input#willvalidate) is false), or it satisfies its constraints. | -| `willValidate` {{readonlyInline}} | _`{{jsxref("Boolean")}}:`_ **Indicates** whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. | +| `name` | _`string`:_ **返回/ 设置** 元素的 [`name`](/zh-CN/docs/Web/HTML/Element/input#name) 属性,包含其名称。 | +| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | `string:` **返回/ 设置** 元素的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性,包含其显示类型。查看 {{ HTMLElement("input") }} 的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性可用值。 | +| `disabled` | _`boolean`:_ **返回/ 设置** 元素的 [`disabled`](/zh-CN/docs/Web/HTML/Element/input#disabled) 属性,表示是否禁用 {{ HTMLElement("input") }}. 该元素的值将不会被提交。也可以查看 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) | +| `autofocus` | `boolean:` **返回/ 设置** 元素的 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性,指定的 {{ HTMLElement("input") }} 在页面加载时应当具有输入焦点,例如通过键入不同的控件。在文档中只有一个表单元素可以拥有 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性。如果 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性被设置为 `hidden` 则无效 (即不可为隐藏控件设置自动焦点). | +| `required` | _`boolean`:_ **返回/ 设置** 元素的 [`required`](/zh-CN/docs/Web/HTML/Element/input#required) 属性,表示用户必填项。 | +| `value` | `string:` **返回/ 设置** 当前控件的值。**提示:** 如果用户输入与预期不同,可能会返回空。 | +| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity state that this element is in. | +| `validationMessage` {{readonlyInline}} | `string:` **Returns** a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ([`willvalidate`](/zh-CN/docs/Web/HTML/Element/input#willvalidate) is false), or it satisfies its constraints. | +| `willValidate` {{readonlyInline}} | _`{{jsxref("Boolean")}}:`_ **Indicates** whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. | -| `checked` | `boolean:` **返回/ 设置** 当前选中状态,当控件[`type`](/zh-CN/docs/Web/HTML/Element/input#type) 是 `checkbox` 或 `radio` 时。 | +| `checked` | `boolean:` **返回/ 设置** 当前选中状态,当控件[`type`](/zh-CN/docs/Web/HTML/Element/input#type) 是 `checkbox` 或 `radio` 时。 | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `defaultChecked` | _`boolean:`_ **返回/ 设置** the default state of a radio button or checkbox as originally specified in HTML that created this object. | | `indeterminate` | `boolean:` **indicates** that the checkbox is neither on nor off. Changes the appearance to resemble a third state. Does not affect the value of the **checked** 属性,and clicking the checkbox will set the value to false. | | `alt` | _`string`:_ **返回/ 设置** 元素的 [`alt`](/zh-CN/docs/Web/HTML/Element/input#alt) 属性,包含 alternative text to use when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image.` | -| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `height` | _`string`:_ **返回/ 设置** 元素的 [`height`](/zh-CN/docs/Web/HTML/Element/input#height) 属性,which defines the height of the image displayed for the button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`. | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `height` | _`string`:_ **返回/ 设置** 元素的 [`height`](/zh-CN/docs/Web/HTML/Element/input#height) 属性,which defines the height of the image displayed for the button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`. | | `src` | `string:` **返回/ 设置** 元素的 [`src`](/zh-CN/docs/Web/HTML/Element/input#src) 属性,which specifies a URI for the location of an image to display on the graphical submit button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`; otherwise it is ignored. | | `width` | `string:` **返回/ 设置** the document's [`width`](/zh-CN/docs/Web/HTML/Element/input#width) 属性,which defines the width of the image displayed for the button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`. | -| `accept` | _`string`:_ **Returns / Sets** 元素的 [`accept`](/zh-CN/docs/Web/HTML/Element/input#accept) 属性,包含 comma-separated list of file types accepted by the server when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `file`. | -| ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `allowdirs` {{non-standard_inline}} | boolean: Part of the non-standard Directory Upload API; **indicates** whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference. | -| `files` | **Returns/accepts** a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload. | -| {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}} | boolean: **Returns** the [`webkitdirectory`](/zh-CN/docs/Web/HTML/Element/input#webkitdirectory) 属性; if true, the file system picker interface only accepts directories instead of files. | -| {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}} | Array of {{domxref("FileSystemEntry")}} objects **describing** the currently-selected files or directories. | +| `accept` | _`string`:_ **Returns / Sets** 元素的 [`accept`](/zh-CN/docs/Web/HTML/Element/input#accept) 属性,包含 comma-separated list of file types accepted by the server when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `file`. | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `allowdirs` {{non-standard_inline}} | boolean: Part of the non-standard Directory Upload API; **indicates** whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference. | +| `files` | **Returns/accepts** a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload. | +| {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}} | boolean: **Returns** the [`webkitdirectory`](/zh-CN/docs/Web/HTML/Element/input#webkitdirectory) 属性; if true, the file system picker interface only accepts directories instead of files. | +| {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}} | Array of {{domxref("FileSystemEntry")}} objects **describing** the currently-selected files or directories. | | `autocomplete` | _`string`:_ **返回/ 设置** 元素的 [`autocomplete`](/zh-CN/docs/Web/HTML/Element/input#autocomplete) 属性,indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `hidden`, `checkbox`, `radio`, `file`, or a button type (`button`, `submit`, `reset`, `image`). Possible values are: "on": the browser can autocomplete the value using previously stored value "off": the user must explicity enter a value | -| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `maxLength` | _`long`:_ **返回/ 设置** 元素的 [`maxlength`](/zh-CN/docs/Web/HTML/Element/input#maxlength) 属性,包含 the **maximum length of characters** (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.) | -| `size` | _`unsigned long`:_ **返回/ 设置** 元素的 [`size`](/zh-CN/docs/Web/HTML/Element/input#size) 属性,包含 **size of the control**. This value is in pixels unless the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `text` or `password`, in which case, it is an integer number of characters. Applies only when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is set to `text`, `search`, `tel`, `url`, `email`, or `password`; otherwise it is ignored. | -| `pattern` | _`string`:_ **返回/ 设置** 元素的 [`pattern`](/zh-CN/docs/Web/HTML/Element/input#pattern) 属性,包含 a **regular expression** that the control's value is checked against. Use the [`title`](/zh-CN/docs/Web/HTML/Element/input#title) 属性 to describe the pattern to help the user. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | -| `placeholder` | _`string`:_ **返回/ 设置** 元素的 [`placeholder`](/zh-CN/docs/Web/HTML/Element/input#placeholder) 属性,包含 a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | -| `readOnly` | _`boolean`:_ **返回/ 设置** 元素的 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) 属性,indicating that the user cannot modify the value of the control. This is ignored if the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type. | -| `min` | _`string`:_ **返回/ 设置** 元素的 [`min`](/zh-CN/docs/Web/HTML/Element/input#min) 属性,包含 the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ([`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性) value. | -| `max` | _`string`:_ **返回/ 设置** 元素的 [`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性,包含 the maximum (numeric or date-time) value for this item, which must not be less than its minimum (**min** 属性) value. | -| `selectionStart` | _`unsigned long`:_ **返回/ 设置** the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element. | -| `selectionEnd` | _`unsigned long`:_ **返回/ 设置** the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position. | -| `selectionDirection` | _`string`:_ **返回/ 设置** the direction in which selection occurred. Possible values are: `"forward"` if selection was performed in the start-to-end direction of the current locale, `"backward"` for the opposite direction, `"none"` if the direction is unknown." | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `maxLength` | _`long`:_ **返回/ 设置** 元素的 [`maxlength`](/zh-CN/docs/Web/HTML/Element/input#maxlength) 属性,包含 the **maximum length of characters** (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.) | +| `size` | _`unsigned long`:_ **返回/ 设置** 元素的 [`size`](/zh-CN/docs/Web/HTML/Element/input#size) 属性,包含 **size of the control**. This value is in pixels unless the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `text` or `password`, in which case, it is an integer number of characters. Applies only when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is set to `text`, `search`, `tel`, `url`, `email`, or `password`; otherwise it is ignored. | +| `pattern` | _`string`:_ **返回/ 设置** 元素的 [`pattern`](/zh-CN/docs/Web/HTML/Element/input#pattern) 属性,包含 a **regular expression** that the control's value is checked against. Use the [`title`](/zh-CN/docs/Web/HTML/Element/input#title) 属性 to describe the pattern to help the user. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | +| `placeholder` | _`string`:_ **返回/ 设置** 元素的 [`placeholder`](/zh-CN/docs/Web/HTML/Element/input#placeholder) 属性,包含 a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | +| `readOnly` | _`boolean`:_ **返回/ 设置** 元素的 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) 属性,indicating that the user cannot modify the value of the control. This is ignored if the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type. | +| `min` | _`string`:_ **返回/ 设置** 元素的 [`min`](/zh-CN/docs/Web/HTML/Element/input#min) 属性,包含 the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ([`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性) value. | +| `max` | _`string`:_ **返回/ 设置** 元素的 [`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性,包含 the maximum (numeric or date-time) value for this item, which must not be less than its minimum (**min** 属性) value. | +| `selectionStart` | _`unsigned long`:_ **返回/ 设置** the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element. | +| `selectionEnd` | _`unsigned long`:_ **返回/ 设置** the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position. | +| `selectionDirection` | _`string`:_ **返回/ 设置** the direction in which selection occurred. Possible values are: `"forward"` if selection was performed in the start-to-end direction of the current locale, `"backward"` for the opposite direction, `"none"` if the direction is unknown." |
diff --git a/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md b/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md index 286ee950e8a867..7c2de33d1b55b5 100644 --- a/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md +++ b/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLInputElement: invalid event' +title: "HTMLInputElement: invalid event" slug: Web/API/HTMLInputElement/invalid_event --- @@ -41,22 +41,28 @@ slug: Web/API/HTMLInputElement/invalid_event ```html
    -
  • -
  • +
  • + +
  • +
-

+ +

``` ### JavaScript ```js -const input = document.querySelector('input') -const log = document.getElementById('log') +const input = document.querySelector("input"); +const log = document.getElementById("log"); -input.addEventListener('invalid', logValue) +input.addEventListener("invalid", logValue); function logValue(e) { - log.textContent += e.target.value + log.textContent += e.target.value; } ``` diff --git a/files/zh-cn/web/api/htmlinputelement/labels/index.md b/files/zh-cn/web/api/htmlinputelement/labels/index.md index 35d49a56887c1c..94603ed757e966 100644 --- a/files/zh-cn/web/api/htmlinputelement/labels/index.md +++ b/files/zh-cn/web/api/htmlinputelement/labels/index.md @@ -23,16 +23,16 @@ var labelElements = input.labels; ```html - + ``` ### JavaScript ```js -window.addEventListener("DOMContentLoaded", function() { +window.addEventListener("DOMContentLoaded", function () { const input = document.getElementById("test"); - for(var i = 0; i < input.labels.length; i++) { + for (var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textContent); // "Label 1" and "Label 2" } }); diff --git a/files/zh-cn/web/api/htmlinputelement/multiple/index.md b/files/zh-cn/web/api/htmlinputelement/multiple/index.md index ba8897b4935298..1ea0c5f5a2133e 100644 --- a/files/zh-cn/web/api/htmlinputelement/multiple/index.md +++ b/files/zh-cn/web/api/htmlinputelement/multiple/index.md @@ -11,15 +11,14 @@ slug: Web/API/HTMLInputElement/multiple ```js // fileInput is a -let fileInput = document.getElementById('myfileinput'); +let fileInput = document.getElementById("myfileinput"); if (fileInput.multiple == true) { - for (let i = 0; i < fileInput.files.length; i++) { // Loop fileInput.files } -// Only one file available + // Only one file available } else { let file = fileInput.files.item(0); } diff --git a/files/zh-cn/web/api/htmlinputelement/select/index.md b/files/zh-cn/web/api/htmlinputelement/select/index.md index 6f7c77d8df7a42..f0d39d38775ad2 100644 --- a/files/zh-cn/web/api/htmlinputelement/select/index.md +++ b/files/zh-cn/web/api/htmlinputelement/select/index.md @@ -20,7 +20,7 @@ element.select() HTML ```html - + ``` @@ -28,7 +28,7 @@ JavaScript ```js function selectText() { - const input = document.getElementById('text-box'); + const input = document.getElementById("text-box"); input.focus(); input.select(); } diff --git a/files/zh-cn/web/api/htmlinputelement/select_event/index.md b/files/zh-cn/web/api/htmlinputelement/select_event/index.md index 6cc3bc876d87d6..fe24a6d64f2551 100644 --- a/files/zh-cn/web/api/htmlinputelement/select_event/index.md +++ b/files/zh-cn/web/api/htmlinputelement/select_event/index.md @@ -42,8 +42,8 @@ slug: Web/API/HTMLInputElement/select_event ## 属性 -| Property | Type | Description | -| ------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------- | +| Property | Type | Description | +| ------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `target` {{readonlyInline}} | [`EventTarget`](/zh-CN/docs/Web/API/EventTarget) | The event target (the topmost target in the DOM tree). | | `type` {{readonlyInline}} | [`DOMString`](/zh-CN/docs/Web/API/DOMString) | The type of event. | | `bubbles` {{readonlyInline}} | [`Boolean`](/zh-CN/docs/Web/API/Boolean) | Whether the event normally bubbles or not. | @@ -56,7 +56,7 @@ slug: Web/API/HTMLInputElement/select_event ### HTML ```html - +

``` @@ -64,13 +64,16 @@ slug: Web/API/HTMLInputElement/select_event ```js function logSelection(event) { - const log = document.getElementById('log'); - const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd); + const log = document.getElementById("log"); + const selection = event.target.value.substring( + event.target.selectionStart, + event.target.selectionEnd, + ); log.textContent = `You selected: ${selection}`; } -const input = document.querySelector('input'); -input.addEventListener('select', logSelection); +const input = document.querySelector("input"); +input.addEventListener("select", logSelection); ``` ### 结果 diff --git a/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md b/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md index 3ada68f2ffb9a5..46a01b8382db4c 100644 --- a/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md +++ b/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md @@ -18,8 +18,8 @@ obj.onselectionchange = function; ```js var selection; -document.onselectionchange = function() { - console.log('New selection made'); +document.onselectionchange = function () { + console.log("New selection made"); selection = document.getSelection(); }; ``` diff --git a/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md b/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md index 9a69057df4f01d..c6875fee642790 100644 --- a/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md +++ b/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md @@ -30,6 +30,7 @@ element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]); - `selectionEnd` - : 被选中的最后一个字符的 _下一个_ 位置索引。如果这个值比元素的 value 长度还大,则会被看作 value 最后一个位置的索引。 - `selectionDirection` {{optional_inline}} + - : 一个表示选择方向的字符串,可能的值有: - `"forward"` diff --git a/files/zh-cn/web/api/htmlinputelement/showpicker/index.md b/files/zh-cn/web/api/htmlinputelement/showpicker/index.md index a0ee83fbb9d8a7..3705e1681773c4 100644 --- a/files/zh-cn/web/api/htmlinputelement/showpicker/index.md +++ b/files/zh-cn/web/api/htmlinputelement/showpicker/index.md @@ -47,7 +47,7 @@ showPicker() 以下代码展示了如何检查 `showPicker()` 是否被支持: ```js -if ('showPicker' in HTMLInputElement.prototype) { +if ("showPicker" in HTMLInputElement.prototype) { // showPicker() is supported. } ``` @@ -118,16 +118,16 @@ document.querySelectorAll("button").forEach((button) => { 以下代码增加了一个事件监听器,当按钮被点击时,调用 `showPicker()`。 ```js - const button = document.querySelector("button"); - const browserInput = document.querySelector("input"); - - button.addEventListener("click", () => { - try { - browserInput.showPicker(); - } catch (error) { - // Fall back to another picker mechanism - } - }); +const button = document.querySelector("button"); +const browserInput = document.querySelector("input"); + +button.addEventListener("click", () => { + try { + browserInput.showPicker(); + } catch (error) { + // Fall back to another picker mechanism + } +}); ``` ### showPicker() 用于 autocomplete @@ -143,16 +143,16 @@ document.querySelectorAll("button").forEach((button) => { 以下代码展示了当按钮被点击时,input 展示的选择器。 ```js - const button = document.querySelector("button"); - const browserInput = document.querySelector("input"); - - button.addEventListener("click", () => { - try { - browserInput.showPicker(); - } catch (error) { - // Fall back to another picker mechanism - } - }); +const button = document.querySelector("button"); +const browserInput = document.querySelector("input"); + +button.addEventListener("click", () => { + try { + browserInput.showPicker(); + } catch (error) { + // Fall back to another picker mechanism + } +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md b/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md index 4b36e14ddd6035..838da120def713 100644 --- a/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md +++ b/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md @@ -11,7 +11,7 @@ slug: Web/API/HTMLInputElement/webkitdirectory ## 语法 ```js - HTMLInputElement.webkitdirectory = boolValue +HTMLInputElement.webkitdirectory = boolValue; ``` ### 值 @@ -51,7 +51,7 @@ slug: Web/API/HTMLInputElement/webkitdirectory 如果用户选择了`PhotoAlbums`,则文件列表上将会包含上面列出的每个文件的{{domxref("File")}}对象,而不是文件目录。条目`PIC2343.jpg`的`webkitRelativePath`属性将会得到`PhotoAlbums/Birthdays/Don's 40th birthday/PIC2343.jpg`的值。即使{{domxref("FileList")}}是扁平的,这也使得知道层次结构成为可能。 -> **备注:** 在 *Chromium < 72* 里,`webkitRelativePath` 的行为表现有所不同。有关更多详细信息,请参见[此 bug](https://bugs.chromium.org/p/chromium/issues/detail?id=124187)。 +> **备注:** 在 _Chromium < 72_ 里,`webkitRelativePath` 的行为表现有所不同。有关更多详细信息,请参见[此 bug](https://bugs.chromium.org/p/chromium/issues/detail?id=124187)。 ## 示例 @@ -67,16 +67,20 @@ slug: Web/API/HTMLInputElement/webkitdirectory ### JavaScript ```js -document.getElementById("filepicker").addEventListener("change", function(event) { - let output = document.getElementById("listing"); - let files = event.target.files; - - for (let i=0; i { +video.addEventListener("abort", () => { console.log(`Abort loading: ${videoSrc}`); }); -const source = document.createElement('source'); -source.setAttribute('src', videoSrc); -source.setAttribute('type', 'video/webm'); +const source = document.createElement("source"); +source.setAttribute("src", videoSrc); +source.setAttribute("type", "video/webm"); video.appendChild(source); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md b/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md index 7fab2809b00522..6f1d5d2062b42a 100644 --- a/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md @@ -22,7 +22,7 @@ AudioTrackList 对象 表示音频/视频的可用音频轨道 以 audio 标签为例 ```html - + ``` 调用 diff --git a/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md b/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md index bd3937bf40fcb9..e686140402479f 100644 --- a/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md @@ -30,7 +30,7 @@ slug: Web/API/HTMLMediaElement/autoplay ... ```js -Xxx.xxx() +Xxx.xxx(); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md b/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md index ad115a56d08815..a4cac55caf6228 100644 --- a/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: canplay' +title: "HTMLMediaElement: canplay" slug: Web/API/HTMLMediaElement/canplay_event --- @@ -43,20 +43,20 @@ slug: Web/API/HTMLMediaElement/canplay_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('canplay', (event) => { - console.log('Video can start, but not sure it will play through.'); +video.addEventListener("canplay", (event) => { + console.log("Video can start, but not sure it will play through."); }); ``` 使用 `oncanplay` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.oncanplay = (event) => { - console.log('Video can start, but not sure it will play through.'); + console.log("Video can start, but not sure it will play through."); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md b/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md index 0e25e393bc46de..5cf1f64d496855 100644 --- a/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: canplaythrough' +title: "HTMLMediaElement: canplaythrough" slug: Web/API/HTMLMediaElement/canplaythrough_event --- @@ -45,22 +45,26 @@ slug: Web/API/HTMLMediaElement/canplaythrough_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('canplaythrough', (event) => { - console.log('I think I can play through the entire ' + - 'video without ever having to stop to buffer.'); +video.addEventListener("canplaythrough", (event) => { + console.log( + "I think I can play through the entire " + + "video without ever having to stop to buffer.", + ); }); ``` 使用 `oncanplaythrough` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.oncanplaythrough = (event) => { - console.log('I think I can play through the entire ' + - 'video without ever having to stop to buffer.'); + console.log( + "I think I can play through the entire " + + "video without ever having to stop to buffer.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md b/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md index c5228b04b6823b..f72bead1eb4afb 100644 --- a/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md @@ -33,8 +33,8 @@ str = audioOrVideo.canPlayType(mediaType); ## 示例 ```js -var obj = document.createElement('video'); -console.log(obj.canPlayType('video/mp4')); // "maybe" +var obj = document.createElement("video"); +console.log(obj.canPlayType("video/mp4")); // "maybe" ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlmediaelement/controls/index.md b/files/zh-cn/web/api/htmlmediaelement/controls/index.md index ea7f61d65e0d7b..be07c49f6d1690 100644 --- a/files/zh-cn/web/api/htmlmediaelement/controls/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/controls/index.md @@ -21,7 +21,7 @@ audio.controls = true; ## 例子 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); obj.controls = true; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md b/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md index e3ebca8b5b1bce..ec0e754770bdba 100644 --- a/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md @@ -20,7 +20,7 @@ var mediaUrl = audioObject.currentSrc; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.currentSrc); // "" ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md b/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md index 54a625631702d1..84cb0616d3cf17 100644 --- a/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md @@ -21,7 +21,7 @@ video.currentTime = 35; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.currentTime); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/duration/index.md b/files/zh-cn/web/api/htmlmediaelement/duration/index.md index dcc8705c8a091d..492ede5df1391c 100644 --- a/files/zh-cn/web/api/htmlmediaelement/duration/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/duration/index.md @@ -10,7 +10,7 @@ slug: Web/API/HTMLMediaElement/duration ## 语法 ```js -var myDuration = audioOrVideo.duration +var myDuration = audioOrVideo.duration; ``` ### 值 @@ -20,7 +20,7 @@ var myDuration = audioOrVideo.duration ## 例子 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.duration); // NaN ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md b/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md index 6e9fd38fb8517b..55f7839a8466de 100644 --- a/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: durationchange 事件' +title: "HTMLMediaElement: durationchange 事件" slug: Web/API/HTMLMediaElement/durationchange_event --- @@ -54,20 +54,20 @@ slug: Web/API/HTMLMediaElement/durationchange_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('durationchange', (event) => { - console.log('Not sure why, but the duration of the video has changed.'); +video.addEventListener("durationchange", (event) => { + console.log("Not sure why, but the duration of the video has changed."); }); ``` 使用 `ondurationchange` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.ondurationchange = (event) => { - console.log('Not sure why, but the duration of the video has changed.'); + console.log("Not sure why, but the duration of the video has changed."); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md b/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md index b18bb79c5d6d70..ea327e2f073488 100644 --- a/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: ended 事件' +title: "HTMLMediaElement: ended 事件" slug: Web/API/HTMLMediaElement/ended_event --- @@ -47,22 +47,26 @@ slug: Web/API/HTMLMediaElement/ended_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('ended', (event) => { - console.log('Video stopped either because 1) it was over, ' + - 'or 2) no further data is available.'); +video.addEventListener("ended", (event) => { + console.log( + "Video stopped either because 1) it was over, " + + "or 2) no further data is available.", + ); }); ``` 使用 `onended` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onended = (event) => { - console.log('Video stopped either because 1) it was over, ' + - 'or 2) no further data is available.'); + console.log( + "Video stopped either because 1) it was over, " + + "or 2) no further data is available.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/error_event/index.md b/files/zh-cn/web/api/htmlmediaelement/error_event/index.md index fdabe9829df19b..4acc88e949c4bf 100644 --- a/files/zh-cn/web/api/htmlmediaelement/error_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/error_event/index.md @@ -14,9 +14,9 @@ slug: Web/API/HTMLMediaElement/error_event 在类似 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 这样的方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('error', (event) => {}); +addEventListener("error", (event) => {}); -onerror = (event) => { }; +onerror = (event) => {}; ``` ## 事件类型 @@ -26,14 +26,14 @@ onerror = (event) => { }; ## 示例 ```js -const video = document.querySelector('video'); -const videoSrc = 'https://path/to/video.webm'; +const video = document.querySelector("video"); +const videoSrc = "https://path/to/video.webm"; -video.addEventListener('error', () => { +video.addEventListener("error", () => { console.error(`Error loading: ${videoSrc}`); }); -video.setAttribute('src', videoSrc); +video.setAttribute("src", videoSrc); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md b/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md index 78d85d27a34a2f..5532be20856805 100644 --- a/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: loadeddata' +title: "HTMLMediaElement: loadeddata" slug: Web/API/HTMLMediaElement/loadeddata_event --- @@ -47,22 +47,26 @@ slug: Web/API/HTMLMediaElement/loadeddata_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('loadeddata', (event) => { - console.log('Yay! readyState just increased to ' + - 'HAVE_CURRENT_DATA or greater for first time.'); +video.addEventListener("loadeddata", (event) => { + console.log( + "Yay! readyState just increased to " + + "HAVE_CURRENT_DATA or greater for first time.", + ); }); ``` 使用 `onloadeddata` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onloadeddata = (event) => { - console.log('Yay! readyState just increased to ' + - 'HAVE_CURRENT_DATA or greater for first time.'); + console.log( + "Yay! readyState just increased to " + + "HAVE_CURRENT_DATA or greater for first time.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md b/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md index 2186f8ea6eb54b..9588f5de99b4c4 100644 --- a/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: loadstart event' +title: "HTMLMediaElement: loadstart event" slug: Web/API/HTMLMediaElement/loadstart_event --- @@ -38,15 +38,13 @@ slug: Web/API/HTMLMediaElement/loadstart_event ```html
+ + - - - -
- - -
- +
+ + +
``` @@ -55,21 +53,21 @@ slug: Web/API/HTMLMediaElement/loadstart_event width: 18rem; height: 5rem; border: 1px solid black; - margin: .2rem; - padding: .2rem; + margin: 0.2rem; + padding: 0.2rem; } .example { display: grid; grid-template-areas: - "button log" - "video log"; + "button log" + "video log"; } button { grid-area: button; width: 10rem; - margin: .5rem 0; + margin: 0.5rem 0; } video { @@ -80,7 +78,7 @@ video { grid-area: log; } -.event-log>label { +.event-log > label { display: block; } ``` @@ -88,32 +86,34 @@ video { #### JS ```js -const loadVideo = document.querySelector('button'); -const video = document.querySelector('video'); -const eventLog = document.querySelector('.event-log-contents'); +const loadVideo = document.querySelector("button"); +const video = document.querySelector("video"); +const eventLog = document.querySelector(".event-log-contents"); let source = null; function handleEvent(event) { - eventLog.textContent = eventLog.textContent + `${event.type}\n`; + eventLog.textContent = eventLog.textContent + `${event.type}\n`; } -video.addEventListener('loadstart', handleEvent); -video.addEventListener('progress', handleEvent); -video.addEventListener('canplay', handleEvent); -video.addEventListener('canplaythrough', handleEvent); - -loadVideo.addEventListener('click', () => { - - if (source) { - document.location.reload(); - } else { - loadVideo.textContent = "Reset example"; - source = document.createElement('source'); - source.setAttribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm'); - source.setAttribute('type', 'video/webm'); - - video.appendChild(source); - } +video.addEventListener("loadstart", handleEvent); +video.addEventListener("progress", handleEvent); +video.addEventListener("canplay", handleEvent); +video.addEventListener("canplaythrough", handleEvent); + +loadVideo.addEventListener("click", () => { + if (source) { + document.location.reload(); + } else { + loadVideo.textContent = "Reset example"; + source = document.createElement("source"); + source.setAttribute( + "src", + "https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm", + ); + source.setAttribute("type", "video/webm"); + + video.appendChild(source); + } }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/loop/index.md b/files/zh-cn/web/api/htmlmediaelement/loop/index.md index 2056debcdb669e..91f03be32054fb 100644 --- a/files/zh-cn/web/api/htmlmediaelement/loop/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/loop/index.md @@ -21,7 +21,7 @@ audio.loop = true; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); obj.loop = true; // true ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/muted/index.md b/files/zh-cn/web/api/htmlmediaelement/muted/index.md index bb18b3f113b95e..51a12d18d38d2e 100644 --- a/files/zh-cn/web/api/htmlmediaelement/muted/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/muted/index.md @@ -21,7 +21,7 @@ A {{domxref("Boolean")}}. `true` 表示被静音, `false` 表示未被静音 ## Example ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.muted); // false ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md b/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md index bc9d52d9c13b47..643f661bb9d11a 100644 --- a/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md @@ -30,19 +30,17 @@ var networkState = audioOrVideo.networkState; ```html ``` ```js -var obj = document.getElementById('example'); - -obj.addEventListener('playing', function() { +var obj = document.getElementById("example"); +obj.addEventListener("playing", function () { if (obj.networkState === 2) { // Still loading... } - }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md b/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md index 49f44c6cf673c9..1cd847a16896e6 100644 --- a/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: pause event' +title: "HTMLMediaElement: pause event" slug: Web/API/HTMLMediaElement/pause_event --- @@ -54,22 +54,26 @@ slug: Web/API/HTMLMediaElement/pause_event 使用 `addEventListener():` ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('pause', (event) => { - console.log('The Boolean paused property is now true. Either the ' + - 'pause() method was called or the autoplay attribute was toggled.'); +video.addEventListener("pause", (event) => { + console.log( + "The Boolean paused property is now true. Either the " + + "pause() method was called or the autoplay attribute was toggled.", + ); }); ``` 使用 `onpause` 事件监听属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onpause = (event) => { - console.log('The Boolean paused property is now true. Either the ' + - 'pause() method was called or the autoplay attribute was toggled.'); + console.log( + "The Boolean paused property is now true. Either the " + + "pause() method was called or the autoplay attribute was toggled.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/paused/index.md b/files/zh-cn/web/api/htmlmediaelement/paused/index.md index f08a74978e68b4..e2d78ffdba03dd 100644 --- a/files/zh-cn/web/api/htmlmediaelement/paused/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/paused/index.md @@ -22,7 +22,7 @@ _仅限暂停状态 因网络原因造成的缓冲状态仍然会告诉你不在 ## 例子 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.paused); // true ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/play_event/index.md b/files/zh-cn/web/api/htmlmediaelement/play_event/index.md index da37bc0739fda6..ce55c513052289 100644 --- a/files/zh-cn/web/api/htmlmediaelement/play_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/play_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: play event' +title: "HTMLMediaElement: play event" slug: Web/API/HTMLMediaElement/play_event --- @@ -52,22 +52,26 @@ slug: Web/API/HTMLMediaElement/play_event Using `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('play', (event) => { - console.log('The Boolean paused property is now false. Either the ' + - 'play() method was called or the autoplay attribute was toggled.'); +video.addEventListener("play", (event) => { + console.log( + "The Boolean paused property is now false. Either the " + + "play() method was called or the autoplay attribute was toggled.", + ); }); ``` Using the `onplay` event handler property: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onplay = (event) => { - console.log('The Boolean paused property is now false. Either the ' + - 'play() method was called or the autoplay attribute was toggled.'); + console.log( + "The Boolean paused property is now false. Either the " + + "play() method was called or the autoplay attribute was toggled.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md b/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md index 02564b9b408542..2c2e734f7d360d 100644 --- a/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md @@ -29,7 +29,7 @@ audio.playbackRate = 1.0; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.playbackRate); // 1 ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md b/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md index 9a788240146b02..dafd6524823274 100644 --- a/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: playing' +title: "HTMLMediaElement: playing" slug: Web/API/HTMLMediaElement/playing_event --- @@ -43,20 +43,20 @@ slug: Web/API/HTMLMediaElement/playing_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('playing', (event) => { - console.log('Video is no longer paused'); +video.addEventListener("playing", (event) => { + console.log("Video is no longer paused"); }); ``` 使用 `onplaying` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onplaying = (event) => { - console.log('Video is no longer paused.'); + console.log("Video is no longer paused."); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md b/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md index 0e55bea97c0a83..eccfba726c44ed 100644 --- a/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: progress event' +title: "HTMLMediaElement: progress event" slug: Web/API/HTMLMediaElement/progress_event --- @@ -34,15 +34,13 @@ slug: Web/API/HTMLMediaElement/progress_event ```html
+ + - - - -
- - -
- +
+ + +
``` @@ -51,21 +49,21 @@ slug: Web/API/HTMLMediaElement/progress_event width: 18rem; height: 5rem; border: 1px solid black; - margin: .2rem; - padding: .2rem; + margin: 0.2rem; + padding: 0.2rem; } .example { display: grid; grid-template-areas: - "button log" - "video log"; + "button log" + "video log"; } button { grid-area: button; width: 10rem; - margin: .5rem 0; + margin: 0.5rem 0; } video { @@ -76,7 +74,7 @@ video { grid-area: log; } -.event-log>label { +.event-log > label { display: block; } ``` @@ -84,32 +82,34 @@ video { ### JavaScript ```js -const loadVideo = document.querySelector('button'); -const video = document.querySelector('video'); -const eventLog = document.querySelector('.event-log-contents'); +const loadVideo = document.querySelector("button"); +const video = document.querySelector("video"); +const eventLog = document.querySelector(".event-log-contents"); let source = null; function handleEvent(event) { - eventLog.textContent = eventLog.textContent + `${event.type}\n`; + eventLog.textContent = eventLog.textContent + `${event.type}\n`; } -video.addEventListener('loadstart', handleEvent); -video.addEventListener('progress', handleEvent); -video.addEventListener('canplay', handleEvent); -video.addEventListener('canplaythrough', handleEvent); - -loadVideo.addEventListener('click', () => { - - if (source) { - document.location.reload(); - } else { - loadVideo.textContent = "Reset example"; - source = document.createElement('source'); - source.setAttribute('src', 'https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4'); - source.setAttribute('type', 'video/mp4'); - - video.appendChild(source); - } +video.addEventListener("loadstart", handleEvent); +video.addEventListener("progress", handleEvent); +video.addEventListener("canplay", handleEvent); +video.addEventListener("canplaythrough", handleEvent); + +loadVideo.addEventListener("click", () => { + if (source) { + document.location.reload(); + } else { + loadVideo.textContent = "Reset example"; + source = document.createElement("source"); + source.setAttribute( + "src", + "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4", + ); + source.setAttribute("type", "video/mp4"); + + video.appendChild(source); + } }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/readystate/index.md b/files/zh-cn/web/api/htmlmediaelement/readystate/index.md index 67f8846ccf9f6c..3e8490dc12cc87 100644 --- a/files/zh-cn/web/api/htmlmediaelement/readystate/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/readystate/index.md @@ -31,19 +31,17 @@ var readyState = audioOrVideo.readyState; ```html ``` ```js -var obj = document.getElementById('example'); +var obj = document.getElementById("example"); -obj.addEventListener('loadeddata', function() { - - if(obj.readyState >= 2) { +obj.addEventListener("loadeddata", function () { + if (obj.readyState >= 2) { obj.play(); } - }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/seekable/index.md b/files/zh-cn/web/api/htmlmediaelement/seekable/index.md index 5856ccdc730a5c..8f403bc772cd04 100644 --- a/files/zh-cn/web/api/htmlmediaelement/seekable/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/seekable/index.md @@ -19,13 +19,13 @@ var seekable = audioOrVideo.seekable; ## 示例 -```html +```js var video = document.querySelector("video"); var timeRangesObject = video.seekable; var timeRanges = []; //遍历所有时间区域并输出数组 for (let count = 0; count < timeRangesObject.length; count ++) { - timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]); + timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]); } ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/src/index.md b/files/zh-cn/web/api/htmlmediaelement/src/index.md index 97b1bfd114bff8..e9b4384b7356d6 100644 --- a/files/zh-cn/web/api/htmlmediaelement/src/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/src/index.md @@ -20,7 +20,7 @@ var mediaUrl = HTMLMediaElement.src; ## Example ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.src); // "" ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md b/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md index 6bdcdb951bf774..9f2a62c7ea9e68 100644 --- a/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: timeupdate' +title: "HTMLMediaElement: timeupdate" slug: Web/API/HTMLMediaElement/timeupdate_event --- @@ -56,20 +56,20 @@ These examples add an event listener for the HTMLMediaElement's `timeupdate` eve Using `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('timeupdate', (event) => { - console.log('The currentTime attribute has been updated. Again.'); +video.addEventListener("timeupdate", (event) => { + console.log("The currentTime attribute has been updated. Again."); }); ``` Using the `ontimeupdate` event handler property: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.ontimeupdate = (event) => { - console.log('The currentTime attribute has been updated. Again.'); + console.log("The currentTime attribute has been updated. Again."); }; ``` diff --git a/files/zh-cn/web/api/htmloptionelement/index.md b/files/zh-cn/web/api/htmloptionelement/index.md index bf13ab5f93b787..ad0c9a77530553 100644 --- a/files/zh-cn/web/api/htmloptionelement/index.md +++ b/files/zh-cn/web/api/htmloptionelement/index.md @@ -13,16 +13,16 @@ slug: Web/API/HTMLOptionElement _继承自其父类属性,{{domxref("HTMLElement")}}._ -| 名称 | 类型 | 描述 | -| ------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `defaultSelected` | {{domxref("Boolean")}} | 包含了[`selected`](/zh-CN/docs/Web/HTML/Element/option#selected) HTML 特性的初始值,指示默认情况下是否选择该选项。 | -| `disabled` | {{domxref("Boolean")}} | 反映了[`disabled`](/zh-CN/docs/Web/HTML/Element/option#disabled) HTML 特性 的值 , 这意味着选项(option)是不可选的。如果一个选项是关闭的{{HTMLElement("optgroup")}}元素的子元素,那么它也可被关闭。 | -| `form`{{readonlyInline}} | {{domxref("HTMLFormElement")}} | 如果该选项是{{HTMLElement("select")}} 元素的后代,则该属性与相应{{DomXref("HTMLSelectElement")}} 对象的`form`属性具有相同的值; 否则为`null`。 | -| `index`{{readonlyInline}} | `long` | 该选项在其所属的选项列表中的位置,以树形顺序排列。如果该选项不是选项列表的一部分,例如为 {{HTMLElement("datalist")}} 元素的一部分时,该值为`0`。 | -| `label` | {{domxref("DOMString")}} | 反映[`label`](/zh-CN/docs/Web/HTML/Element/option#label) HTML 特性的值,该属性为选项提供了一个标签。如果没有特别设置此属性,读取它返回元素的文本内容。 | -| `selected` | {{domxref("Boolean")}} | 表示当前该 option 是否被选择。 | -| `text` | {{domxref("DOMString")}} | 包含元素的文本内容。 | -| `value` | {{domxref("DOMString")}} | 反映[`value`](/zh-CN/docs/Web/HTML/Element/option#value) HTML 特性的值(如果存在);否则反映{{domxref("Node.textContent")}} 特性的值。 | +| 名称 | 类型 | 描述 | +| ------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `defaultSelected` | {{domxref("Boolean")}} | 包含了[`selected`](/zh-CN/docs/Web/HTML/Element/option#selected) HTML 特性的初始值,指示默认情况下是否选择该选项。 | +| `disabled` | {{domxref("Boolean")}} | 反映了[`disabled`](/zh-CN/docs/Web/HTML/Element/option#disabled) HTML 特性 的值 , 这意味着选项(option)是不可选的。如果一个选项是关闭的{{HTMLElement("optgroup")}}元素的子元素,那么它也可被关闭。 | +| `form`{{readonlyInline}} | {{domxref("HTMLFormElement")}} | 如果该选项是{{HTMLElement("select")}} 元素的后代,则该属性与相应{{DomXref("HTMLSelectElement")}} 对象的`form`属性具有相同的值; 否则为`null`。 | +| `index`{{readonlyInline}} | `long` | 该选项在其所属的选项列表中的位置,以树形顺序排列。如果该选项不是选项列表的一部分,例如为 {{HTMLElement("datalist")}} 元素的一部分时,该值为`0`。 | +| `label` | {{domxref("DOMString")}} | 反映[`label`](/zh-CN/docs/Web/HTML/Element/option#label) HTML 特性的值,该属性为选项提供了一个标签。如果没有特别设置此属性,读取它返回元素的文本内容。 | +| `selected` | {{domxref("Boolean")}} | 表示当前该 option 是否被选择。 | +| `text` | {{domxref("DOMString")}} | 包含元素的文本内容。 | +| `value` | {{domxref("DOMString")}} | 反映[`value`](/zh-CN/docs/Web/HTML/Element/option#value) HTML 特性的值(如果存在);否则反映{{domxref("Node.textContent")}} 特性的值。 | ## 方法 diff --git a/files/zh-cn/web/api/htmlscriptelement/index.md b/files/zh-cn/web/api/htmlscriptelement/index.md index a42696f98271ef..8dd92e5ec91a04 100644 --- a/files/zh-cn/web/api/htmlscriptelement/index.md +++ b/files/zh-cn/web/api/htmlscriptelement/index.md @@ -128,16 +128,21 @@ _没有具体的方法;属性从其父类继承,{{domxref("HTMLElement")}}。_ 让我们创建一个名为 importScript 的函数,它能够在一个文档中导入新的脚本,创建一个{{HTMLElement("script")}} 节点,并立即插入到宿主{{HTMLElement("script")}} 之前 (通过 {{domxref("document.currentScript")}} 可以获取宿主 script 标签)。这些脚本将**异步**执行。更多细节,请参见 defer 和 async 属性。 ```js -function loadError (oError) { +function loadError(oError) { throw new URIError("The script " + oError.target.src + " is not accessible."); } -function importScript (sSrc, fOnload) { +function importScript(sSrc, fOnload) { var oScript = document.createElement("script"); - oScript.type = "text\/javascript"; + oScript.type = "text/javascript"; oScript.onerror = loadError; - if (fOnload) { oScript.onload = fOnload; } - document.currentScript.parentNode.insertBefore(oScript, document.currentScript); + if (fOnload) { + oScript.onload = fOnload; + } + document.currentScript.parentNode.insertBefore( + oScript, + document.currentScript, + ); oScript.src = sSrc; } ``` @@ -148,20 +153,22 @@ function importScript (sSrc, fOnload) { ```js var importScript = (function (oHead) { - - function loadError (oError) { - throw new URIError("The script " + oError.target.src + " is not accessible."); + function loadError(oError) { + throw new URIError( + "The script " + oError.target.src + " is not accessible.", + ); } return function (sSrc, fOnload) { var oScript = document.createElement("script"); - oScript.type = "text\/javascript"; + oScript.type = "text/javascript"; oScript.onerror = loadError; - if (fOnload) { oScript.onload = fOnload; } + if (fOnload) { + oScript.onload = fOnload; + } oHead.appendChild(oScript); oScript.src = sSrc; - } - + }; })(document.head || document.getElementsByTagName("head")[0]); ``` @@ -169,7 +176,14 @@ var importScript = (function (oHead) { ```js importScript("myScript1.js"); -importScript("myScript2.js", /* onload function: */ function () { alert("You read this alert because the script \"myScript2.js\" has been correctly loaded."); }); +importScript( + "myScript2.js", + /* onload function: */ function () { + alert( + 'You read this alert because the script "myScript2.js" has been correctly loaded.', + ); + }, +); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlselectelement/index.md b/files/zh-cn/web/api/htmlselectelement/index.md index 4ecce05fdf5b8d..05b2f2f8f15d7f 100644 --- a/files/zh-cn/web/api/htmlselectelement/index.md +++ b/files/zh-cn/web/api/htmlselectelement/index.md @@ -91,13 +91,13 @@ _这个接口从 {{domxref("HTMLElement")}},{{domxref("Element")}} 和 {{domxr */ -var select = document.getElementById('s'); +var select = document.getElementById("s"); // return the index of the selected option console.log(select.selectedIndex); // 1 // return the value of the selected option -console.log(select.options[select.selectedIndex].value) // Second +console.log(select.options[select.selectedIndex].value); // Second ``` A better way to track changes to the user's selection is to watch for the {{domxref("HTMLElement/change_event", "change")}} event to occur on the ` - - - + + + + + + + + + + + +
NameOccupation
BobPlumber
JimRoofer
NameOccupation
BobPlumber
JimRoofer
``` ### JavaScript ```js -let table = document.querySelector('table'); +let table = document.querySelector("table"); table.deleteTHead(); ``` diff --git a/files/zh-cn/web/api/htmltableelement/rows/index.md b/files/zh-cn/web/api/htmltableelement/rows/index.md index 324f026ce1eb48..88c80edcdbe6a9 100644 --- a/files/zh-cn/web/api/htmltableelement/rows/index.md +++ b/files/zh-cn/web/api/htmltableelement/rows/index.md @@ -20,7 +20,7 @@ HTMLCollectionObject = table.rows ```js myrows = mytable.rows; firstRow = mytable.rows[0]; -lastRow = mytable.rows[mytable.rows.length-1]; +lastRow = mytable.rows[mytable.rows.length - 1]; ``` ## Specification diff --git a/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md b/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md index 191d1b13dc540f..7ba50aa5e1e578 100644 --- a/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md +++ b/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md @@ -12,7 +12,7 @@ slug: Web/API/HTMLTableRowElement/rowIndex ## 语法 ```js -var index = HTMLTableRowElement.rowIndex +var index = HTMLTableRowElement.rowIndex; ``` ### 返回值 @@ -28,15 +28,30 @@ var index = HTMLTableRowElement.rowIndex ```html - + + + + - - - + + + + + + + + + + + + - + + + +
商品 价格
商品价格
香蕉 $2
橘子 $8
西冷牛排 $20
香蕉$2
橘子$8
西冷牛排$20
总计 $30
总计$30
``` @@ -44,7 +59,7 @@ var index = HTMLTableRowElement.rowIndex ### JavaScript ```js -let rows = document.querySelectorAll('tr'); +let rows = document.querySelectorAll("tr"); rows.forEach((row) => { let z = document.createElement("td"); diff --git a/files/zh-cn/web/api/htmltextareaelement/index.md b/files/zh-cn/web/api/htmltextareaelement/index.md index c0027a8cf56f5e..182d2f6e5380a7 100644 --- a/files/zh-cn/web/api/htmltextareaelement/index.md +++ b/files/zh-cn/web/api/htmltextareaelement/index.md @@ -11,49 +11,49 @@ slug: Web/API/HTMLTextAreaElement ## 属性 -| `form` {{readonlyInline}} | `object:` 返回一个父表单元素的引用。如果这个元素没有被包含在一个表单元素中,则这个值是页面中任意一个 {{HTMLElement("form")}} 元素的 [`id`](/zh-CN/docs/Web/HTML/Element/form#id) 属性或者 `null`。 | -| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `type` {{readonlyInline}} | `string:` 返回字符串 `textarea`。 | -| `value` | `string:` Returns / Sets the raw value contained in the control. | -| `textLength` {{readonlyInline}} | `long:` Returns the codepoint length of the control's `value`. Same as `calling value.length` | -| `defaultValue` | `string:` Returns / Sets the control's default value, which behaves like the {{domxref("Node.textContent")}} property. | -| `placeholder` | `string:` 返回/设置元素[`placeholder`](/zh-CN/docs/Web/HTML/Element/textarea#placeholder) 属性,用于提示用户在组件中应该输入什么。 | -| `rows` | `unsigned long:` Returns / Sets the element's [`rows`](/zh-CN/docs/Web/HTML/Element/textarea#rows) attribute, indicating the number of visible text lines for the control. | -| `cols` | `unsigned long:` Returns / Sets the element's [`cols`](/zh-CN/docs/Web/HTML/Element/textarea#cols) attribute, indicating the visible width of the text area. | -| `autofocus` | `boolean:` Returns / Sets the element's [`autofocus`](/zh-CN/docs/Web/HTML/Element/textarea#autofocus) attribute, indicating that the control should have input focus when the page loads | -| `name` | `string:` Returns / Sets the element's [`name`](/zh-CN/docs/Web/HTML/Element/textarea#name) attribute, containing the name of the control. | -| `disabled` | `boolean:` Returns / Sets the element's [`disabled`](/zh-CN/docs/Web/HTML/Element/textarea#disabled) attribute, indicating that the control is not available for interaction. | -| {{domxref("HTMLTextAreaElement.labels")}}{{ReadOnlyInline}} | {{domxref("NodeList")}}: Returns a list of label elements associated with this select element. | -| `maxLength` | `long:` Returns / Sets the element's [`maxlength`](/zh-CN/docs/Web/HTML/Element/textarea#maxlength) attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes. | -| `minLength` | `long:` Returns / Sets the element's [`minlength`](/zh-CN/docs/Web/HTML/Element/textarea#minlength) attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes. | -| `accessKey` | `string:` Returns / Sets the element's [`accesskey`](/zh-CN/docs/Web/HTML/Element/textarea#accesskey) attribute. | -| `readOnly` | `boolean:` Returns / Sets the element's [`readonly`](/zh-CN/docs/Web/HTML/Element/textarea#readonly) attribute, indicating that the user cannot modify the value of the control. | -| `required` | `boolean:` Returns / Sets the element's [`required`](/zh-CN/docs/Web/HTML/Element/textarea#required) attribute, indicating that the user must specify a value before submitting the form. | -| `tabIndex` | `long:` Returns / Sets the position of the element in the tabbing navigation order for the current document. | -| `selectionStart` | `unsigned long:` Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the first argument, and `selectionEnd` as the second argument. | -| `selectionEnd` | `unsigned long:` Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the second argument, and `selectionStart` as the first argument. | -| `selectionDirection` | `string:` Returns / Sets the direction in which selection occurred. This is `"forward"` if selection was performed in the start-to-end direction of the current locale, or `"backward"` for the opposite direction. This can also be `"none"` if the direction is unknown." | -| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity states that this element is in. | -| `willValidate` {{readonlyInline}} | `boolean:` Returns whether the element is a candidate for constraint validation. `false` if any conditions bar it from constraint validation, including its `readOnly` or `disabled` property is `true`. | -| `validationMessage` {{readonlyInline}} | `string:` Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints. | -| `autocomplete` {{experimental_inline}} | | -| `autocapitalize` {{experimental_inline}} | `string:` Returns / Sets the element's capitalization behavior for user input. Valid values are: `none`, `off`, `characters`, `words`, `sentences`. | -| `inputMode` {{experimental_inline}} | | -| `wrap` | `string:` Returns / Sets the [`wrap`](/zh-CN/docs/Web/HTML/Element/textarea#wrap) HTML attribute, indicating how the control wraps text. | +| `form` {{readonlyInline}} | `object:` 返回一个父表单元素的引用。如果这个元素没有被包含在一个表单元素中,则这个值是页面中任意一个 {{HTMLElement("form")}} 元素的 [`id`](/zh-CN/docs/Web/HTML/Element/form#id) 属性或者 `null`。 | +| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` {{readonlyInline}} | `string:` 返回字符串 `textarea`。 | +| `value` | `string:` Returns / Sets the raw value contained in the control. | +| `textLength` {{readonlyInline}} | `long:` Returns the codepoint length of the control's `value`. Same as `calling value.length` | +| `defaultValue` | `string:` Returns / Sets the control's default value, which behaves like the {{domxref("Node.textContent")}} property. | +| `placeholder` | `string:` 返回/设置元素[`placeholder`](/zh-CN/docs/Web/HTML/Element/textarea#placeholder) 属性,用于提示用户在组件中应该输入什么。 | +| `rows` | `unsigned long:` Returns / Sets the element's [`rows`](/zh-CN/docs/Web/HTML/Element/textarea#rows) attribute, indicating the number of visible text lines for the control. | +| `cols` | `unsigned long:` Returns / Sets the element's [`cols`](/zh-CN/docs/Web/HTML/Element/textarea#cols) attribute, indicating the visible width of the text area. | +| `autofocus` | `boolean:` Returns / Sets the element's [`autofocus`](/zh-CN/docs/Web/HTML/Element/textarea#autofocus) attribute, indicating that the control should have input focus when the page loads | +| `name` | `string:` Returns / Sets the element's [`name`](/zh-CN/docs/Web/HTML/Element/textarea#name) attribute, containing the name of the control. | +| `disabled` | `boolean:` Returns / Sets the element's [`disabled`](/zh-CN/docs/Web/HTML/Element/textarea#disabled) attribute, indicating that the control is not available for interaction. | +| {{domxref("HTMLTextAreaElement.labels")}}{{ReadOnlyInline}} | {{domxref("NodeList")}}: Returns a list of label elements associated with this select element. | +| `maxLength` | `long:` Returns / Sets the element's [`maxlength`](/zh-CN/docs/Web/HTML/Element/textarea#maxlength) attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes. | +| `minLength` | `long:` Returns / Sets the element's [`minlength`](/zh-CN/docs/Web/HTML/Element/textarea#minlength) attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes. | +| `accessKey` | `string:` Returns / Sets the element's [`accesskey`](/zh-CN/docs/Web/HTML/Element/textarea#accesskey) attribute. | +| `readOnly` | `boolean:` Returns / Sets the element's [`readonly`](/zh-CN/docs/Web/HTML/Element/textarea#readonly) attribute, indicating that the user cannot modify the value of the control. | +| `required` | `boolean:` Returns / Sets the element's [`required`](/zh-CN/docs/Web/HTML/Element/textarea#required) attribute, indicating that the user must specify a value before submitting the form. | +| `tabIndex` | `long:` Returns / Sets the position of the element in the tabbing navigation order for the current document. | +| `selectionStart` | `unsigned long:` Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the first argument, and `selectionEnd` as the second argument. | +| `selectionEnd` | `unsigned long:` Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the second argument, and `selectionStart` as the first argument. | +| `selectionDirection` | `string:` Returns / Sets the direction in which selection occurred. This is `"forward"` if selection was performed in the start-to-end direction of the current locale, or `"backward"` for the opposite direction. This can also be `"none"` if the direction is unknown." | +| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity states that this element is in. | +| `willValidate` {{readonlyInline}} | `boolean:` Returns whether the element is a candidate for constraint validation. `false` if any conditions bar it from constraint validation, including its `readOnly` or `disabled` property is `true`. | +| `validationMessage` {{readonlyInline}} | `string:` Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints. | +| `autocomplete` {{experimental_inline}} | | +| `autocapitalize` {{experimental_inline}} | `string:` Returns / Sets the element's capitalization behavior for user input. Valid values are: `none`, `off`, `characters`, `words`, `sentences`. | +| `inputMode` {{experimental_inline}} | | +| `wrap` | `string:` Returns / Sets the [`wrap`](/zh-CN/docs/Web/HTML/Element/textarea#wrap) HTML attribute, indicating how the control wraps text. | The two properties `tabIndex` and `accessKey` are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on `HTMLTextAreaElement` in DOM Level 2 HTML and earlier specifications. ## 方法 -| {{domxref("HTMLElement/blur", "blur()")}} | Removes focus from the control; keystrokes will subsequently go nowhere. | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| {{domxref("HTMLElement/focus", "focus()")}} | Gives focus to the control; keystrokes will subsequently go to this element. | -| {{domxref("HTMLInputElement/select", "select()")}} | Selects the contents of the control. | -| {{domxref("HTMLInputElement/setRangeText", "setRangeText()")}} | Replaces a range of text in the element with new text. | +| {{domxref("HTMLElement/blur", "blur()")}} | Removes focus from the control; keystrokes will subsequently go nowhere. | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| {{domxref("HTMLElement/focus", "focus()")}} | Gives focus to the control; keystrokes will subsequently go to this element. | +| {{domxref("HTMLInputElement/select", "select()")}} | Selects the contents of the control. | +| {{domxref("HTMLInputElement/setRangeText", "setRangeText()")}} | Replaces a range of text in the element with new text. | | {{domxref("HTMLInputElement/setSelectionRange", "setSelectionRange()")}} | Selects a range of text in the element (but does not focus it). | -| `checkValidity()` | Returns `false` if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable `invalid` event at the control. It returns `true` if the control is not a candidate for constraint validation, or if it satisfies its constraints. | -| `reportValidity()` | This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`. | -| `setCustomValidity(DOMstring)` | Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. | +| `checkValidity()` | Returns `false` if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable `invalid` event at the control. It returns `true` if the control is not a candidate for constraint validation, or if it satisfies its constraints. | +| `reportValidity()` | This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`. | +| `setCustomValidity(DOMstring)` | Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. | The two methods `blur()` and `focus()` are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on `HTMLTextAreaElement` in DOM Level 2 HTML and earlier specifications. @@ -73,7 +73,7 @@ Make a textarea autogrow while typing: JavaScript function: ```js -function autoGrow (oField) { +function autoGrow(oField) { if (oField.scrollHeight > oField.clientHeight) { oField.style.height = oField.scrollHeight + "px"; } @@ -111,9 +111,21 @@ JavaScript function: ```js function insertMetachars(sStartTag, sEndTag) { - var bDouble = arguments.length > 1, oMsgInput = document.myForm.myTxtArea, nSelStart = oMsgInput.selectionStart, nSelEnd = oMsgInput.selectionEnd, sOldText = oMsgInput.value; - oMsgInput.value = sOldText.substring(0, nSelStart) + (bDouble ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag : sStartTag) + sOldText.substring(nSelEnd); - oMsgInput.setSelectionRange(bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, (bDouble ? nSelEnd : nSelStart) + sStartTag.length); + var bDouble = arguments.length > 1, + oMsgInput = document.myForm.myTxtArea, + nSelStart = oMsgInput.selectionStart, + nSelEnd = oMsgInput.selectionEnd, + sOldText = oMsgInput.value; + oMsgInput.value = + sOldText.substring(0, nSelStart) + + (bDouble + ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag + : sStartTag) + + sOldText.substring(nSelEnd); + oMsgInput.setSelectionRange( + bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, + (bDouble ? nSelEnd : nSelStart) + sStartTag.length, + ); oMsgInput.focus(); } ``` @@ -132,8 +144,38 @@ HTML: ```html
-

Bold | Italic | URL | code | smile | etc. etc. ]

-

+

+ [ Bold + | + Italic + | + URL + | + code + | smile | + etc. etc. ] +

+

+ +

``` @@ -147,25 +189,43 @@ First, create a function that takes the text field and a key event as input and ```js function checkRows(oField, oKeyEvent) { - var nKey = (oKeyEvent || /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }).keyCode, - + var nKey = ( + oKeyEvent || + /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 } + ).keyCode, // put here the maximum number of characters per line: nCols = 30, // put here the maximum number of lines: nRows = 5, - - nSelS = oField.selectionStart, nSelE = oField.selectionEnd, - sVal = oField.value, nLen = sVal.length, - + nSelS = oField.selectionStart, + nSelE = oField.selectionEnd, + sVal = oField.value, + nLen = sVal.length, nBackward = nSelS >= nCols ? nSelS - nCols : 0, - nDeltaForw = sVal.substring(nBackward, nSelS).search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1, + nDeltaForw = + sVal + .substring(nBackward, nSelS) + .search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1, nRowStart = nBackward + nDeltaForw, - aReturns = (sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)).match(/\n/g), + aReturns = ( + sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length) + ).match(/\n/g), nRowEnd = nSelE + nRowStart + nCols - nSelS, - sRow = sVal.substring(nRowStart, nSelS) + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd), - bKeepCols = nKey === 13 || nLen + 1 < nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && (sRow.length < nCols || (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n")))); - - return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && ((nKey > 32 && nKey < 41) || bKeepCols); + sRow = + sVal.substring(nRowStart, nSelS) + + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd), + bKeepCols = + nKey === 13 || + nLen + 1 < nCols || + /\n/.test(sRow) || + ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && + (sRow.length < nCols || + (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n")))); + + return ( + (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && + ((nKey > 32 && nKey < 41) || bKeepCols) + ); } ``` @@ -173,9 +233,13 @@ In the HTML we just need to hook our function to the `onkeypress` event and spec ```html
-

Textarea with fixed number of characters per line:
- +

+ Textarea with fixed number of characters per line:
+

``` diff --git a/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md b/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md index a553c62c6555e2..d2a7ae5bfd7ceb 100644 --- a/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLVideoElement: enterpictureinpicture event' +title: "HTMLVideoElement: enterpictureinpicture event" slug: Web/API/HTMLVideoElement/enterpictureinpicture_event --- @@ -14,9 +14,9 @@ slug: Web/API/HTMLVideoElement/enterpictureinpicture_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}}使用事件的名称,或者设置事件处理器属性。 ```js -addEventListener('enterpictureinpicture', event => { }); +addEventListener("enterpictureinpicture", (event) => {}); -onenterpictureinpicture = event => { }; +onenterpictureinpicture = (event) => {}; ``` ## 事件类型 diff --git a/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md b/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md index 1a37ea316ba2ed..a39e73e9c77297 100644 --- a/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLVideoElement: leavepictureinpicture event' +title: "HTMLVideoElement: leavepictureinpicture event" slug: Web/API/HTMLVideoElement/leavepictureinpicture_event --- @@ -14,9 +14,9 @@ slug: Web/API/HTMLVideoElement/leavepictureinpicture_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}}等方法中使用事件方法名,或者设置事件处理器属性。 ```js -addEventListener('leavepictureinpicture', event => { }); +addEventListener("leavepictureinpicture", (event) => {}); -onleavepictureinpicture = event => { }; +onleavepictureinpicture = (event) => {}; ``` ## 事件类型 diff --git a/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md b/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md index d035eed9eb5753..380620a4a96320 100644 --- a/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md @@ -5,14 +5,14 @@ slug: Web/API/HTMLVideoElement/requestPictureInPicture {{ APIRef("HTML DOM") }} - **{{domxref("HTMLVideoElement")}}** 接口提供的 **`requestPictureInPicture()`** 方法会发出异步请求,并以画中画的模式显示视频。 +**{{domxref("HTMLVideoElement")}}** 接口提供的 **`requestPictureInPicture()`** 方法会发出异步请求,并以画中画的模式显示视频。 该方法不能保证视频进入画中画。如果授予了进入画中画的权限,则将返回一个 {{jsxref("Promise")}},最终完成后将收到一个 {{domxref("HTMLVideoElement.enterpictureinpicture_event", "enterpictureinpicture")}} 事件,来表示它现在处于画中画状态。 ## 语法 ```js -requestPictureInPicture() +requestPictureInPicture(); ``` ### 返回值 @@ -25,10 +25,13 @@ requestPictureInPicture() ```js function enterPictureInPicture() { - videoElement.requestPictureInPicture() - .then(pictureInPictureWindow => { - pictureInPictureWindow.addEventListener("resize", () => onPipWindowResize(), false); - }) + videoElement.requestPictureInPicture().then((pictureInPictureWindow) => { + pictureInPictureWindow.addEventListener( + "resize", + () => onPipWindowResize(), + false, + ); + }); } ``` diff --git a/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md b/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md index 544b133c4ec52a..c284a6d35b7980 100644 --- a/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md @@ -34,15 +34,19 @@ slug: Web/API/HTMLVideoElement/videoHeight ```js let v = document.getElementById("myVideo"); -v.addEventListener("resize", ev => { - let w = v.videoWidth; - let h = v.videoHeight; - - if (w && h) { - v.style.width = w; - v.style.height = h; - } -}, false); +v.addEventListener( + "resize", + (ev) => { + let w = v.videoWidth; + let h = v.videoHeight; + + if (w && h) { + v.style.width = w; + v.style.height = h; + } + }, + false, +); ``` 请注意,只有当 `videoWidth` 和 `videoHeight` 都不是 0 的情况,才会应用更改。 diff --git a/files/zh-cn/web/api/idbcursor/direction/index.md b/files/zh-cn/web/api/idbcursor/direction/index.md index a9808968597f20..7e2fa4b558e508 100644 --- a/files/zh-cn/web/api/idbcursor/direction/index.md +++ b/files/zh-cn/web/api/idbcursor/direction/index.md @@ -38,24 +38,28 @@ prev ```js function backwards() { - list.innerHTML = ''; - var transaction = db.transaction(['rushAlbumList'], 'readonly'); - var objectStore = transaction.objectStore('rushAlbumList'); + list.innerHTML = ""; + var transaction = db.transaction(["rushAlbumList"], "readonly"); + var objectStore = transaction.objectStore("rushAlbumList"); - objectStore.openCursor(null,'prev').onsuccess = function(event) { + objectStore.openCursor(null, "prev").onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = '' + cursor.value.albumTitle + ', ' + cursor.value.year; - list.appendChild(listItem); - - console.log(cursor.direction); - cursor.continue(); - } else { - console.log('Entries displayed backwards.'); - } + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = + "" + + cursor.value.albumTitle + + ", " + + cursor.value.year; + list.appendChild(listItem); + + console.log(cursor.direction); + cursor.continue(); + } else { + console.log("Entries displayed backwards."); + } }; -}; +} ``` ## Specifications diff --git a/files/zh-cn/web/api/idbcursor/index.md b/files/zh-cn/web/api/idbcursor/index.md index 7a384e7c94cb74..9d2377f256cb9f 100644 --- a/files/zh-cn/web/api/idbcursor/index.md +++ b/files/zh-cn/web/api/idbcursor/index.md @@ -50,22 +50,22 @@ slug: Web/API/IDBCursor ```js function displayData() { - var transaction = db.transaction(['rushAlbumList'], "readonly"); - var objectStore = transaction.objectStore('rushAlbumList'); + var transaction = db.transaction(["rushAlbumList"], "readonly"); + var objectStore = transaction.objectStore("rushAlbumList"); - objectStore.openCursor().onsuccess = function(event) { + objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = cursor.value.albumTitle + ", " + cursor.value.year; list.appendChild(listItem); cursor.continue(); } else { - console.log('Entries all displayed.'); + console.log("Entries all displayed."); } }; -}; +} ``` ## Specifications diff --git a/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md b/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md index 0e051f61c00a76..0a0962439da729 100644 --- a/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md +++ b/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md @@ -44,47 +44,47 @@ var objectStore = IDBDatabase.createObjectStore(name, options); This method may raise a 此方法可能会抛出一个 {{domxref("DOMException")}} 带有以下所列其中一种类型的 {{domxref("DOMError")}} : -| Exception | Description | -| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `InvalidStateError` | 在非`versionchange`事务中调用时发生。在一些旧版本的 Webkit 浏览器,你必须先调用{{APIRef("IDBVersionChangeRequest.setVersion")}}方法。 | +| Exception | Description | +| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `InvalidStateError` | 在非`versionchange`事务中调用时发生。在一些旧版本的 Webkit 浏览器,你必须先调用{{APIRef("IDBVersionChangeRequest.setVersion")}}方法。 | | `TransactionInactiveError` | 如果对不存在的源数据库发出请求(例如,已被删除的)。此外,在 Firefox 版本小于 41 中,会抛出误导性的 `InvalidStateError` 错误,这一问题现已修复(请参阅 [Firefox bug 1176165](https://bugzil.la/1176165))。 | -| `ConstraintError` | 数据库中已存同名的对象存储(名字区分大小写) | -| `InvalidAccessError` | 如果 `autoIncrement` 设置为 true,并且 keyPath 是空字符串或包含空字符串的数组。 | +| `ConstraintError` | 数据库中已存同名的对象存储(名字区分大小写) | +| `InvalidAccessError` | 如果 `autoIncrement` 设置为 true,并且 keyPath 是空字符串或包含空字符串的数组。 | ## Example ```js - // 打开一个数据库 - var request = window.indexedDB.open("toDoList", 4); - - // This handler is called when a new version of the database - // is created, either when one has not been created before - // or when a new version number is submitted by calling - // window.indexedDB.open(). - // This handler is only supported in recent browsers. - request.onupgradeneeded = function(event) { - var db = event.target.result; - - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; - }; +// 打开一个数据库 +var request = window.indexedDB.open("toDoList", 4); + +// This handler is called when a new version of the database +// is created, either when one has not been created before +// or when a new version number is submitted by calling +// window.indexedDB.open(). +// This handler is only supported in recent browsers. +request.onupgradeneeded = function (event) { + var db = event.target.result; + + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; + }; - // Create an objectStore for this database + // Create an objectStore for this database - var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); - // define what data items the objectStore will contain + // define what data items the objectStore will contain - objectStore.createIndex("hours", "hours", { unique: false }); - objectStore.createIndex("minutes", "minutes", { unique: false }); - objectStore.createIndex("day", "day", { unique: false }); - objectStore.createIndex("month", "month", { unique: false }); - objectStore.createIndex("year", "year", { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); - objectStore.createIndex("notified", "notified", { unique: false }); + objectStore.createIndex("notified", "notified", { unique: false }); - note.innerHTML += '
  • Object store created.
  • '; - }; + note.innerHTML += "
  • Object store created.
  • "; +}; ``` ## Specification diff --git a/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md b/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md index 84ca0ed06eaecc..68cc165bb6da60 100644 --- a/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md +++ b/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md @@ -26,11 +26,11 @@ dbInstance.deleteObjectStore(name); 此方法可能会引发下列 {{domxref("DOMException")}} 异常: -| Exception | Description | -| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `InvalidStateError` | Occurs if the method was not called from a `versionchange` transaction callback. For older WebKit browsers, you must call {{ APIRef("IDBVersionChangeRequest.setVersion")}} first. | +| Exception | Description | +| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `InvalidStateError` | Occurs if the method was not called from a `versionchange` transaction callback. For older WebKit browsers, you must call {{ APIRef("IDBVersionChangeRequest.setVersion")}} first. | | `TransactionInactiveError` | Occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) In Firefox previous to version 41, an `InvalidStateError` was raised in this case as well, which was misleading; this has now been fixed (see [Firefox bug 1176165](https://bugzil.la/1176165).) | -| `NotFoundError` | You are trying to delete an object store that does not exist. Names are case sensitive. | +| `NotFoundError` | You are trying to delete an object store that does not exist. Names are case sensitive. | ## 示例 @@ -39,7 +39,7 @@ var dbName = "sampleDB"; var dbVersion = 2; var request = indexedDB.open(dbName, dbVersion); -request.onupgradeneeded = function(e) { +request.onupgradeneeded = function (e) { var db = request.result; if (e.oldVersion < 1) { db.createObjectStore("store1"); diff --git a/files/zh-cn/web/api/idbdatabase/index.md b/files/zh-cn/web/api/idbdatabase/index.md index c8f0edc35ec1db..081fa6a73c954f 100644 --- a/files/zh-cn/web/api/idbdatabase/index.md +++ b/files/zh-cn/web/api/idbdatabase/index.md @@ -53,54 +53,54 @@ IndexedDB 中的 **`IDBDatabase`** 接口提供一个到 [数据库的连接](/z ```js // 我们先打开一个数据库 - var DBOpenRequest = window.indexedDB.open("toDoList", 4); +var DBOpenRequest = window.indexedDB.open("toDoList", 4); - // 当数据库打开出错/成功时,以下两个事件处理程序将分别对 IDBDatabase 对象进行下一步操作 - DBOpenRequest.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; - }; +// 当数据库打开出错/成功时,以下两个事件处理程序将分别对 IDBDatabase 对象进行下一步操作 +DBOpenRequest.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; +}; - DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; - // 将打开数据库的结果存储在 db 变量中,该变量将在后面的代码中被频繁使用 - db = DBOpenRequest.result; + // 将打开数据库的结果存储在 db 变量中,该变量将在后面的代码中被频繁使用 + db = DBOpenRequest.result; - // 运行 displayData() 方法,用 IDB 中已经存在的所有待办事项列表数据填充到任务列表中 - displayData(); - }; + // 运行 displayData() 方法,用 IDB 中已经存在的所有待办事项列表数据填充到任务列表中 + displayData(); +}; - // 当试图打开一个尚未被创建的数据库,或者试图连接一个数据库还没被创立的版本时,onupgradeneeded 事件会被触发 +// 当试图打开一个尚未被创建的数据库,或者试图连接一个数据库还没被创立的版本时,onupgradeneeded 事件会被触发 - DBOpenRequest.onupgradeneeded = function(event) { - var db = event.target.result; +DBOpenRequest.onupgradeneeded = function (event) { + var db = event.target.result; - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; - }; + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; + }; - // 使用 IDBDatabase.createObjectStore 方法,可创建一个对象存储区 + // 使用 IDBDatabase.createObjectStore 方法,可创建一个对象存储区 - var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); - // 定义 objectStore 将包含哪些数据项 + // 定义 objectStore 将包含哪些数据项 - objectStore.createIndex("hours", "hours", { unique: false }); - objectStore.createIndex("minutes", "minutes", { unique: false }); - objectStore.createIndex("day", "day", { unique: false }); - objectStore.createIndex("month", "month", { unique: false }); - objectStore.createIndex("year", "year", { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); - objectStore.createIndex("notified", "notified", { unique: false }); + objectStore.createIndex("notified", "notified", { unique: false }); - note.innerHTML += '
  • Object store created.
  • '; - }; + note.innerHTML += "
  • Object store created.
  • "; +}; ``` 下一行打开数据库上的事务,然后打开一个对象存储,然后我们可以在其中操作数据。 ```js - var objectStore = db.transaction('toDoList').objectStore('toDoList'); +var objectStore = db.transaction("toDoList").objectStore("toDoList"); ``` ## 规范 diff --git a/files/zh-cn/web/api/idbfactory/index.md b/files/zh-cn/web/api/idbfactory/index.md index c7d4817ccc3c78..67dbdf711b5dae 100644 --- a/files/zh-cn/web/api/idbfactory/index.md +++ b/files/zh-cn/web/api/idbfactory/index.md @@ -29,23 +29,31 @@ In the following code snippet, we make a request to open a database, and include var note = document.querySelector("ul"); // In the following line, you should include the prefixes of implementations you want to test. -window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; +window.indexedDB = + window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: -window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; -window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; +window.IDBTransaction = + window.IDBTransaction || + window.webkitIDBTransaction || + window.msIDBTransaction; +window.IDBKeyRange = + window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*) // Let us open version 4 of our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); // these two event handlers act on the database being opened successfully, or not -DBOpenRequest.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; +DBOpenRequest.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike. db = request.result; diff --git a/files/zh-cn/web/api/idbfactory/open/index.md b/files/zh-cn/web/api/idbfactory/open/index.md index 8914d43543d55b..cd6c160f67482a 100644 --- a/files/zh-cn/web/api/idbfactory/open/index.md +++ b/files/zh-cn/web/api/idbfactory/open/index.md @@ -11,8 +11,8 @@ slug: Web/API/IDBFactory/open 1. 指定数据库已经存在时: - - 等待 {{domxref("versionchange")}} 操作完成。 - - 如果数据库已计划删除,那等着删除完成。 + - 等待 {{domxref("versionchange")}} 操作完成。 + - 如果数据库已计划删除,那等着删除完成。 2. 如果已有数据库版本高于给定的 `version`,中止操作并返回类型为 `VersionError` 的 `DOMError`。 3. 如果已有数据库版本低于给定的 `version`,触发一个 `versionchange` 操作。 @@ -48,7 +48,10 @@ var request = window.indexedDB.open("toDoList", 4); For the experimental version with `options` (see below): ```js -var request = window.indexedDB.open("toDoList", {version: 4, storage: "temporary"}); +var request = window.indexedDB.open("toDoList", { + version: 4, + storage: "temporary", +}); ``` ## 参数 diff --git a/files/zh-cn/web/api/idbkeyrange/index.md b/files/zh-cn/web/api/idbkeyrange/index.md index b73a56b1c36885..7e937f4fac9c04 100644 --- a/files/zh-cn/web/api/idbkeyrange/index.md +++ b/files/zh-cn/web/api/idbkeyrange/index.md @@ -9,17 +9,17 @@ slug: Web/API/IDBKeyRange 键范围可以是单个值,也可以是具有上界、下界或端点的范围。如果键范围同时有上界或下界,那么它是有界的,否则是无界的。有界键范围可以是开放的(不包含端点)或闭合的(包含了端点)。要检索一定范围内的所有键值,可以使用以下的代码结构: -| Range | Code | -| --------------------------- | ----------------------------------------------------------------- | -| All keys ≤ **x** | {{domxref("IDBKeyRange.upperBound")}}`(x)` | -| All keys < **x** | {{domxref("IDBKeyRange.upperBound")}}`(x, true)` | -| All keys ≥ **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y)` | -| All keys > **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y, true)` | +| Range | Code | +| --------------------------- | ----------------------------------------------------- | +| All keys ≤ **x** | {{domxref("IDBKeyRange.upperBound")}}`(x)` | +| All keys < **x** | {{domxref("IDBKeyRange.upperBound")}}`(x, true)` | +| All keys ≥ **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y)` | +| All keys > **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y, true)` | | All keys ≥ **x** && ≤ **y** | {{domxref("IDBKeyRange.bound")}}`(x, y)` | | All keys > **x** &&< **y** | {{domxref("IDBKeyRange.bound")}}`(x, y, true, true)` | | All keys > **x** && ≤ **y** | {{domxref("IDBKeyRange.bound")}}`(x, y, true, false)` | | All keys ≥ **x** &&< **y** | {{domxref("IDBKeyRange.bound")}}`(x, y, false, true)` | -| The key = **z** | {{domxref("IDBKeyRange.only")}}`(z)` | +| The key = **z** | {{domxref("IDBKeyRange.only")}}`(z)` | 如果以下条件为 true,则键包含在键范围中: @@ -76,19 +76,20 @@ slug: Web/API/IDBKeyRange function displayData() { var keyRangeValue = IDBKeyRange.bound("A", "F"); - var transaction = db.transaction(['fThings'], 'readonly'); - var objectStore = transaction.objectStore('fThings'); + var transaction = db.transaction(["fThings"], "readonly"); + var objectStore = transaction.objectStore("fThings"); - objectStore.openCursor(keyRangeValue).onsuccess = function(event) { + objectStore.openCursor(keyRangeValue).onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = '' + cursor.value.fThing + ', ' + cursor.value.fRating; + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = + "" + cursor.value.fThing + ", " + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { - console.log('Entries all displayed.'); + console.log("Entries all displayed."); } }; } diff --git a/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md b/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md index 0873a3afb34ebf..6cc90bcb010133 100644 --- a/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md +++ b/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md @@ -46,22 +46,23 @@ var myIDBKeyRange = IDBKeyRange.lowerBound(lower, open); function displayData() { var keyRangeValue = IDBKeyRange.lowerBound("F"); - var transaction = db.transaction(['fThings'], 'readonly'); - var objectStore = transaction.objectStore('fThings'); + var transaction = db.transaction(["fThings"], "readonly"); + var objectStore = transaction.objectStore("fThings"); - objectStore.openCursor(keyRangeValue).onsuccess = function(event) { + objectStore.openCursor(keyRangeValue).onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = '' + cursor.value.fThing + ', ' + cursor.value.fRating; - list.appendChild(listItem); - - cursor.continue(); - } else { - console.log('Entries all displayed.'); - } - }; + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = + "" + cursor.value.fThing + ", " + cursor.value.fRating; + list.appendChild(listItem); + + cursor.continue(); + } else { + console.log("Entries all displayed."); + } }; +} ``` ## Specification diff --git a/files/zh-cn/web/api/idbobjectstore/add/index.md b/files/zh-cn/web/api/idbobjectstore/add/index.md index ab64307b09b104..08d0dccf59af96 100644 --- a/files/zh-cn/web/api/idbobjectstore/add/index.md +++ b/files/zh-cn/web/api/idbobjectstore/add/index.md @@ -98,8 +98,8 @@ var request = objectStore.add(value, key); // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -111,18 +111,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready to insert into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -131,11 +142,11 @@ function addData() { // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## Specification diff --git a/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md index d0e76518c19cdd..d257300720c8e5 100644 --- a/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md +++ b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md @@ -36,8 +36,8 @@ var myAutoIncrement = objectStore.autoIncrement; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -49,18 +49,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready to insert into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -70,11 +81,11 @@ function addData() { // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/get/index.md b/files/zh-cn/web/api/idbobjectstore/get/index.md index dbd68d5d0c7377..812b57caf81a8c 100644 --- a/files/zh-cn/web/api/idbobjectstore/get/index.md +++ b/files/zh-cn/web/api/idbobjectstore/get/index.md @@ -32,10 +32,10 @@ var request = objectStore.get(key); 此方法可能会引发以下类型之一的 {{domxref("DOMException")}} : -| Exception | Description | -| ------------------------ | ------------------------------------------------------------------------- | +| Exception | Description | +| ------------------------ | -------------------------------------------------------------- | | TransactionInactiveError | This {{domxref("IDBObjectStore")}}'s transaction is inactive. | -| DataError | The key or key range provided contains an invalid key. | +| DataError | The key or key range provided contains an invalid key. | | `InvalidStateError` | The {{domxref("IDBObjectStore")}} has been deleted or removed. | ## 例子 @@ -46,8 +46,8 @@ var request = objectStore.get(key); // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -62,12 +62,13 @@ function getData() { var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error: ' + transaction.error + '
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error: " + transaction.error + "
  • "; }; // create an object store on the transaction @@ -76,14 +77,13 @@ function getData() { // Make a request to get a record by key from the object store var objectStoreRequest = objectStore.get("Walk dog"); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; var myRecord = objectStoreRequest.result; }; - -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/index.md b/files/zh-cn/web/api/idbobjectstore/index.md index 924788a9f7e6af..b7f9d15e30e0d9 100644 --- a/files/zh-cn/web/api/idbobjectstore/index.md +++ b/files/zh-cn/web/api/idbobjectstore/index.md @@ -13,27 +13,27 @@ slug: Web/API/IDBObjectStore ## 方法预览 -| `IDBRequest add (in any value, in optional any key) raises (DOMException);` | -| -------------------------------------------------------------------------------------------------------------------------------------------- | -| `IDBRequest clear() raises (DOMException);` | -| `IDBRequest count (in optional any key) raises (DOMException);` | +| `IDBRequest add (in any value, in optional any key) raises (DOMException);` | +| ------------------------------------------------------------------------------------------------------------------- | +| `IDBRequest clear() raises (DOMException);` | +| `IDBRequest count (in optional any key) raises (DOMException);` | | `IDBIndex createIndex (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (DOMException);` | -| ` IDBRequest delete (in any key) raises (DOMException); ` | -| `void deleteIndex (in any DOMString indexName) raises (DOMException); | -| `IDBRequest get (in any key) raises (DOMException);` | +| `IDBRequest delete (in any key) raises (DOMException);` | +| `void deleteIndex (in any DOMString indexName) raises (DOMException); | +| `IDBRequest get (in any key) raises (DOMException);` | | `IDBIndex index (in DOMString name) raises (DOMException);` | -| `IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);` | -| `IDBRequest put (in any value, in optional any key) raises (DOMException);` | +| `IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);` | +| `IDBRequest put (in any value, in optional any key) raises (DOMException);` | ## 属性 -| Attribute | Type | Description | -| --------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| Attribute | Type | Description | +| --------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `indexNames` | `readonly DOMStringList` | 表中对象的[索引](/zh-CN/IndexedDB#gloss_index)名列表。 | | `keyPath` | `readonly` [`DOMString`](/En/DOM/DOMString) | 表中的[键路径](/zh-CN/IndexedDB#gloss_key_path),如果该属性为 null,每次操作表时必须提供一个键名。 | -| `name` | `readonly` [`DOMString`](/En/DOM/DOMString) | 表名 | -| `transaction` | `readonly IDBTransaction` | 事务的名称,该表属于此事务。 | -| `autoIncrement` | `readonly boolean` | 表中自增字段的值 | +| `name` | `readonly` [`DOMString`](/En/DOM/DOMString) | 表名 | +| `transaction` | `readonly IDBTransaction` | 事务的名称,该表属于此事务。 | +| `autoIncrement` | `readonly boolean` | 表中自增字段的值 | ## 方法 @@ -239,7 +239,7 @@ This method may raise a [DOMException](/zh-CN/docs/DOM/DOMException) with a [DOM > **备注:** If the key that identifies the record is a Number, the key passed to the delete method must be a Number too, and not a String. So for example you might need to do the following: > > ```js -> var key_val = '42'; +> var key_val = "42"; > var key = Number(key_val); > objectstore.delete(key); > ``` @@ -446,8 +446,8 @@ This example shows a variety of different uses of object stores, from updating t // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in db. db = DBOpenRequest.result; @@ -457,11 +457,11 @@ DBOpenRequest.onsuccess = function(event) { // the database needs to be created Either one has not // been created before, or a new version number has been // submitted via the window.indexedDB.open line above -DBOpenRequest.onupgradeneeded = function(event) { +DBOpenRequest.onupgradeneeded = function (event) { var db = event.target.result; - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; // Create an objectStore for this database @@ -478,24 +478,33 @@ DBOpenRequest.onupgradeneeded = function(event) { objectStore.createIndex("notified", "notified", { unique: false }); - note.innerHTML += '
  • Object store created.
  • '; + note.innerHTML += "
  • Object store created.
  • "; }; // Create a new item to add in to the object store var newItem = [ - { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: 'December', year: 2013, notified: "no" } + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done -transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; +transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; -transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; +transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -503,9 +512,9 @@ var objectStore = transaction.objectStore("toDoList"); // make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); -objectStoreRequest.onsuccess = function(event) { - note.innerHTML += '
  • Request successful .
  • '; -} +objectStoreRequest.onsuccess = function (event) { + note.innerHTML += "
  • Request successful .
  • "; +}; ``` ## Specifications diff --git a/files/zh-cn/web/api/idbobjectstore/indexnames/index.md b/files/zh-cn/web/api/idbobjectstore/indexnames/index.md index 482ab3e74e7f3a..a6b98bb9b70e04 100644 --- a/files/zh-cn/web/api/idbobjectstore/indexnames/index.md +++ b/files/zh-cn/web/api/idbobjectstore/indexnames/index.md @@ -27,8 +27,8 @@ var myindexNames = objectStore.indexNames; // 让我们来打开我们的数据库 var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // 将打开数据库的结果存储在 db 变量中 // 下面经常用到这个 @@ -40,19 +40,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // 创建一个新对象以准备插入到 IDB 中 - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // 打开读/写数据库事务,准备添加数据 var transaction = db.transaction(["toDoList"], "readwrite"); // 当所有事情都完成时,报告事务完成的成功情况 - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // 在事务上创建对象存储 @@ -62,11 +72,11 @@ function addData() { // 请求将 newItem 对象 添加到对象存储区 var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // 报告我们请求的成功 - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/keypath/index.md b/files/zh-cn/web/api/idbobjectstore/keypath/index.md index 0f9eab311a7780..b19579d9ceaa01 100644 --- a/files/zh-cn/web/api/idbobjectstore/keypath/index.md +++ b/files/zh-cn/web/api/idbobjectstore/keypath/index.md @@ -33,8 +33,8 @@ var mykeyPath = objectStore.keyPath; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -46,18 +46,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready to insert into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -67,11 +78,11 @@ function addData() { // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/opencursor/index.md b/files/zh-cn/web/api/idbobjectstore/opencursor/index.md index f3b61f521907a9..3bf93542c8ba47 100644 --- a/files/zh-cn/web/api/idbobjectstore/opencursor/index.md +++ b/files/zh-cn/web/api/idbobjectstore/opencursor/index.md @@ -32,11 +32,11 @@ var request = ObjectStore.openCursor(query, direction); 此方法可能引起以下类型之一的 {{domxref("DOMException")}} : -| 异常 | 描述 | -| -------------------------- | ----------------------------------------------------------------------------------------- | +| 异常 | 描述 | +| -------------------------- | --------------------------------------------------------------------- | | `InvalidStateError` | 此 {{domxref("IDBObjectStore")}} 或{{domxref("IDBIndex")}} 已被删除。 | -| `TransactionInactiveError` | 此 {{domxref("IDBObjectStore")}} 的事务处于非活动状态。 | -| `DataError` | 指定的键或键范围无效。 | +| `TransactionInactiveError` | 此 {{domxref("IDBObjectStore")}} 的事务处于非活动状态。 | +| `DataError` | 指定的键或键范围无效。 | ## 例子 @@ -46,9 +46,9 @@ var request = ObjectStore.openCursor(query, direction); var transaction = db.transaction("name", "readonly"); var objectStore = transaction.objectStore("name"); var request = objectStore.openCursor(); -request.onsuccess = function(event) { +request.onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { + if (cursor) { // cursor.value 包含正在被遍历的当前记录 // 这里你可以对 result 做些什么 cursor.continue(); diff --git a/files/zh-cn/web/api/idbobjectstore/put/index.md b/files/zh-cn/web/api/idbobjectstore/put/index.md index 92fc720f8bd3a3..65038b3037bcad 100644 --- a/files/zh-cn/web/api/idbobjectstore/put/index.md +++ b/files/zh-cn/web/api/idbobjectstore/put/index.md @@ -113,12 +113,14 @@ The following example requests a given record title; when that request is succes var title = "Walk dog"; // Open up a transaction as usual -var objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList'); +var objectStore = db + .transaction(["toDoList"], "readwrite") + .objectStore("toDoList"); // Get the to-do list object that has this title as it's title var objectStoreTitleRequest = objectStore.get(title); -objectStoreTitleRequest.onsuccess = function() { +objectStoreTitleRequest.onsuccess = function () { // Grab the data object returned as the result var data = objectStoreTitleRequest.result; @@ -129,10 +131,13 @@ objectStoreTitleRequest.onsuccess = function() { var updateTitleRequest = objectStore.put(data); // Log the transaction that originated this request - console.log("The transaction that originated this request is " + updateTitleRequest.transaction); + console.log( + "The transaction that originated this request is " + + updateTitleRequest.transaction, + ); // When this new request succeeds, run the displayData() function again to update the display - updateTitleRequest.onsuccess = function() { + updateTitleRequest.onsuccess = function () { displayData(); }; }; diff --git a/files/zh-cn/web/api/idbopendbrequest/index.md b/files/zh-cn/web/api/idbopendbrequest/index.md index 4b09645602388b..af10b33997fc56 100644 --- a/files/zh-cn/web/api/idbopendbrequest/index.md +++ b/files/zh-cn/web/api/idbopendbrequest/index.md @@ -37,12 +37,12 @@ var db; var DBOpenRequest = window.indexedDB.open("toDoList", 4); // these event handlers act on the database being opened. -DBOpenRequest.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; +DBOpenRequest.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db // variable. This is used a lot below @@ -58,11 +58,11 @@ DBOpenRequest.onsuccess = function(event) { // been created before, or a new version number has been // submitted via the window.indexedDB.open line above // it is only implemented in recent browsers -DBOpenRequest.onupgradeneeded = function(event) { +DBOpenRequest.onupgradeneeded = function (event) { var db = this.result; - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; // Create an objectStore for this database diff --git a/files/zh-cn/web/api/idbtransaction/complete_event/index.md b/files/zh-cn/web/api/idbtransaction/complete_event/index.md index 865b1d1152e04d..f47075a62ed3b3 100644 --- a/files/zh-cn/web/api/idbtransaction/complete_event/index.md +++ b/files/zh-cn/web/api/idbtransaction/complete_event/index.md @@ -1,5 +1,5 @@ --- -title: 'IDBTransaction: complete event' +title: "IDBTransaction: complete event" slug: Web/API/IDBTransaction/complete_event --- @@ -36,39 +36,46 @@ Using {{DOMxRef("EventTarget.addEventListener", "addEventListener()")}}: ```js // Open the database -const DBOpenRequest = window.indexedDB.open('toDoList', 4); +const DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onupgradeneeded = event => { +DBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { - console.log('Error creating database'); + console.log("Error creating database"); }; // Create an objectStore for this database - var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); // define what data items the objectStore will contain - objectStore.createIndex('hours', 'hours', { unique: false }); - objectStore.createIndex('minutes', 'minutes', { unique: false }); - objectStore.createIndex('day', 'day', { unique: false }); - objectStore.createIndex('month', 'month', { unique: false }); - objectStore.createIndex('year', 'year', { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); }; -DBOpenRequest.onsuccess = event => { +DBOpenRequest.onsuccess = (event) => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data - const transaction = db.transaction(['toDoList'], 'readwrite'); + const transaction = db.transaction(["toDoList"], "readwrite"); // add a listener for `complete` - transaction.addEventListener('complete', event => { - console.log('Transaction was competed'); + transaction.addEventListener("complete", (event) => { + console.log("Transaction was competed"); }); - const objectStore = transaction.objectStore('toDoList'); - const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; + const objectStore = transaction.objectStore("toDoList"); + const newItem = { + taskTitle: "my task", + hours: 10, + minutes: 10, + day: 10, + month: "January", + year: 2019, + }; const objectStoreRequest = objectStore.add(newItem); }; ``` @@ -77,39 +84,46 @@ Using the {{DOMxRef("IDBTransaction.oncomplete", "oncomplete")}} property: ```js // Open the database -const DBOpenRequest = window.indexedDB.open('toDoList', 4); +const DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onupgradeneeded = event => { +DBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { - console.log('Error creating database'); + console.log("Error creating database"); }; // Create an objectStore for this database - var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); // define what data items the objectStore will contain - objectStore.createIndex('hours', 'hours', { unique: false }); - objectStore.createIndex('minutes', 'minutes', { unique: false }); - objectStore.createIndex('day', 'day', { unique: false }); - objectStore.createIndex('month', 'month', { unique: false }); - objectStore.createIndex('year', 'year', { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); }; -DBOpenRequest.onsuccess = event => { +DBOpenRequest.onsuccess = (event) => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data - const transaction = db.transaction(['toDoList'], 'readwrite'); + const transaction = db.transaction(["toDoList"], "readwrite"); // add a listener for `complete` - transaction.oncomplete = event => { - console.log('Transaction was competed'); + transaction.oncomplete = (event) => { + console.log("Transaction was competed"); }; - const objectStore = transaction.objectStore('toDoList'); - const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; + const objectStore = transaction.objectStore("toDoList"); + const newItem = { + taskTitle: "my task", + hours: 10, + minutes: 10, + day: 10, + month: "January", + year: 2019, + }; const objectStoreRequest = objectStore.add(newItem); }; ``` diff --git a/files/zh-cn/web/api/idbtransaction/db/index.md b/files/zh-cn/web/api/idbtransaction/db/index.md index 8d495cd727bd14..4d186bb6e78b6d 100644 --- a/files/zh-cn/web/api/idbtransaction/db/index.md +++ b/files/zh-cn/web/api/idbtransaction/db/index.md @@ -27,8 +27,8 @@ In the following code snippet, we open a read/write transaction on our database // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -40,18 +40,30 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready for being inserted into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed: database modification finished.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += + "
  • Transaction completed: database modification finished.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -60,15 +72,15 @@ function addData() { // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of the request (this does not mean the item // has been stored successfully in the DB - for that you need transaction.onsuccess) - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; // Return the database (IDBDatabase) connection with which this transaction is associated transaction.db; -}; +} ``` ## Specification diff --git a/files/zh-cn/web/api/idbtransaction/index.md b/files/zh-cn/web/api/idbtransaction/index.md index 80950f2ed4c18c..829d42e522e7dc 100644 --- a/files/zh-cn/web/api/idbtransaction/index.md +++ b/files/zh-cn/web/api/idbtransaction/index.md @@ -16,8 +16,8 @@ If you must ensure durability for some reason (e.g. you're storing critical data ```js var trans1 = db.transaction("foo", "readwrite"); var trans2 = db.transaction("foo", "readwrite"); -var objectStore2 = trans2.objectStore("foo") -var objectStore1 = trans1.objectStore("foo") +var objectStore2 = trans2.objectStore("foo"); +var objectStore1 = trans1.objectStore("foo"); objectStore2.put("2", "key"); objectStore1.put("1", "key"); ``` @@ -82,16 +82,17 @@ Transactions can fail for a fixed number of reasons, all of which (except the us Transactions 可使用以下三种模式中的一种: -| 常量 | 值 | 描述 | -| -------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `READ_ONLY` | "readonly"(0 in Chrome) | 允许读取数据,不改变。 | -| `READ_WRITE` | "readwrite"(1 in Chrome) | 允许读取和写入现有数据存储,数据被改变。 | +| 常量 | 值 | 描述 | +| ---------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `READ_ONLY` | "readonly"(0 in Chrome) | 允许读取数据,不改变。 | +| `READ_WRITE` | "readwrite"(1 in Chrome) | 允许读取和写入现有数据存储,数据被改变。 | | `VERSION_CHANGE` | "versionchange"(2 in Chrome) | 允许执行任何操作,包括删除和创建对象存储和索引。此模式是用于开始使用[IDBDatabase](/zh-CN/docs/IndexedDB/IDBDatabase) 的 [`setVersion()`](/zh-CN/docs/IndexedDB/IDBDatabase#setVersion)方法更新版本号事务。这种模式的事务无法与其他事务并发运行。这种模式下的事务被称为“升级事务”。 | 即使目前这些常量已经被废弃,但如果你需要使用它,则需要提供向下兼容方案 (in Chrome [the change was made in version 21](http://peter.sh/2012/05/tab-sizing-string-values-for-indexeddb-and-chrome-21/))。你应当防止出现对象不存在的情况: ```js -var myIDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" }; +var myIDBTransaction = window.IDBTransaction || + window.webkitIDBTransaction || { READ_WRITE: "readwrite" }; ``` ## Example @@ -102,8 +103,8 @@ In the following code snippet, we open a read/write transaction on our database // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. This is used a lot below db = DBOpenRequest.result; @@ -114,19 +115,30 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready for being inserted into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed: database modification finished.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += + "
  • Transaction completed: database modification finished.
  • "; }; - - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -135,11 +147,11 @@ function addData() { // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our new item going into the database - note.innerHTML += '
  • New item added to database.
  • '; + note.innerHTML += "
  • New item added to database.
  • "; }; -}; +} ``` ## Specifications diff --git a/files/zh-cn/web/api/imagedata/width/index.md b/files/zh-cn/web/api/imagedata/width/index.md index dc1d3d9b9d1285..a23175f75ab73f 100644 --- a/files/zh-cn/web/api/imagedata/width/index.md +++ b/files/zh-cn/web/api/imagedata/width/index.md @@ -17,7 +17,7 @@ imagedata.width ```js var imagedata = new ImageData(100, 100); -imagedata.width // 100 +imagedata.width; // 100 ``` ## 规范 diff --git a/files/zh-cn/web/api/indexeddb/index.md b/files/zh-cn/web/api/indexeddb/index.md index 4df48e8e41e908..d103b9fcaf46fa 100644 --- a/files/zh-cn/web/api/indexeddb/index.md +++ b/files/zh-cn/web/api/indexeddb/index.md @@ -22,10 +22,10 @@ var IDBFactory = self.indexedDB; ```js var db; function openDB() { - var DBOpenRequest = window.indexedDB.open('toDoList'); - DBOpenRequest.onsuccess = function(e) { - db = DBOpenRequest.result; - } + var DBOpenRequest = window.indexedDB.open("toDoList"); + DBOpenRequest.onsuccess = function (e) { + db = DBOpenRequest.result; + }; } ``` diff --git a/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md b/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md index 1d48fd77447c52..9890936d2ecf9b 100644 --- a/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md +++ b/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md @@ -115,11 +115,11 @@ function checkDeadlines() { First we grab the current date and time by creating a blank `Date` object. Easy huh? It's about to get a bit more complex. ```js - var minuteCheck = now.getMinutes(); - var hourCheck = now.getHours(); - var dayCheck = now.getDate(); - var monthCheck = now.getMonth(); - var yearCheck = now.getFullYear(); +var minuteCheck = now.getMinutes(); +var hourCheck = now.getHours(); +var dayCheck = now.getDate(); +var monthCheck = now.getMonth(); +var yearCheck = now.getFullYear(); ``` The `Date` object has a number of methods to extract various parts of the date and time inside it. Here we fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (`getDate()` is needed for this, as `getDay()` returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (`getFullYear()` is needed; `getYear()` is deprecated, and returns a weird value that is not much use to anyone!) @@ -136,38 +136,39 @@ The `Date` object has a number of methods to extract various parts of the date a Next we create another IndexedDB `objectStore`, and use the `openCursor()` method to open a cursor, which is basically a way in IndexedDB to iterate through all the items in the store. We then loop through all the items in the cursor for as long as there is a valid item left in the cursor. ```js - switch(cursor.value.month) { - case "January": - var monthNumber = 0; - break; - case "February": - var monthNumber = 1; - break; - - // other lines removed from listing for brevity - - case "December": - var monthNumber = 11; - break; - default: - alert('Incorrect month entered in database.'); - } +switch (cursor.value.month) { + case "January": + var monthNumber = 0; + break; + case "February": + var monthNumber = 1; + break; + + // other lines removed from listing for brevity + + case "December": + var monthNumber = 11; + break; + default: + alert("Incorrect month entered in database."); +} ``` 我们要做的第一件事是将我们存储在数据库中的月份名称转换为 JavaScript 将理解的月份号码。如前所述,JavaScript Date 对象将月份值创建为 0 到 11 之间的数字。 ```js - if(+(cursor.value.hours) == hourCheck && - +(cursor.value.minutes) == minuteCheck && - +(cursor.value.day) == dayCheck && - monthNumber == monthCheck && - cursor.value.year == yearCheck && - notified == "no") { - - // If the numbers all do match, run the createNotification() - // function to create a system notification - createNotification(cursor.value.taskTitle); - } +if ( + +cursor.value.hours == hourCheck && + +cursor.value.minutes == minuteCheck && + +cursor.value.day == dayCheck && + monthNumber == monthCheck && + cursor.value.year == yearCheck && + notified == "no" +) { + // If the numbers all do match, run the createNotification() + // function to create a system notification + createNotification(cursor.value.taskTitle); +} ``` With the current time and date segments that we want to check against the IndexedDB stored values all assembled, it is time to perform the checks. We want all the values to match before we show the user some kind of notification to tell them their deadline is up. diff --git a/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md b/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md index 943f44efef82e7..2390b78508aa8b 100644 --- a/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md +++ b/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md @@ -35,11 +35,19 @@ IndexedDB 鼓励使用的基本模式如下所示: ```js // In the following line, you should include the prefixes of implementations you want to test. -window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; +window.indexedDB = + window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: -window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; -window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange +window.IDBTransaction = + window.IDBTransaction || + window.webkitIDBTransaction || + window.msIDBTransaction; +window.IDBKeyRange = + window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*) ``` @@ -47,7 +55,9 @@ window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.ms ```js if (!window.indexedDB) { - window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.") + window.alert( + "Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.", + ); } ``` @@ -77,10 +87,10 @@ open 请求不会立即打开数据库或者开始一个事务。对 `open()` 几乎所有我们产生的请求我们在处理的时候首先要做的就是添加成功和失败处理函数: ```js -request.onerror = function(event) { +request.onerror = function (event) { // Do something with request.errorCode! }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { // Do something with request.result! }; ``` @@ -96,10 +106,10 @@ IndexedDB 的 API 被设计来尽可能地减少对错误处理的需求,所 ```js var db; var request = indexedDB.open("MyTestDatabase"); -request.onerror = function(event) { +request.onerror = function (event) { alert("Why didn't you allow my web app to use IndexedDB?!"); }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { db = event.target.result; }; ``` @@ -109,7 +119,7 @@ request.onsuccess = function(event) { 如上文所述,错误事件遵循冒泡机制。错误事件都是针对产生这些错误的请求的,然后事件冒泡到事务,然后最终到达数据库对象。如果你希望避免为所有的请求都增加错误处理程序,你可以替代性的仅对数据库对象添加一个错误处理程序,像这样: ```js -db.onerror = function(event) { +db.onerror = function (event) { // Generic error handler for all errors targeted at this database's // requests! alert("Database error: " + event.target.errorCode); @@ -126,7 +136,7 @@ db.onerror = function(event) { ```js // 该事件仅在较新的浏览器中实现了 -request.onupgradeneeded = function(event) { +request.onupgradeneeded = function (event) { // 保存 IDBDataBase 接口 var db = event.target.result; @@ -166,7 +176,7 @@ WebKit/Blink 支持当前版本的规范,同时 Chrome 23+ 、Opera 17+ 以及 // 我们的客户数据看起来像这样。 const customerData = [ { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" }, - { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" } + { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }, ]; ``` @@ -179,10 +189,10 @@ const dbName = "the_name"; var request = indexedDB.open(dbName, 2); -request.onerror = function(event) { +request.onerror = function (event) { // 错误处理 }; -request.onupgradeneeded = function(event) { +request.onupgradeneeded = function (event) { var db = event.target.result; // 建立一个对象仓库来存储我们客户的相关信息,我们选择 ssn 作为键路径(key path) @@ -196,10 +206,12 @@ request.onupgradeneeded = function(event) { objectStore.createIndex("email", "email", { unique: true }); // 使用事务的 oncomplete 事件确保在插入数据前对象仓库已经创建完毕 - objectStore.transaction.oncomplete = function(event) { + objectStore.transaction.oncomplete = function (event) { // 将数据保存到新创建的对象仓库 - var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers"); - customerData.forEach(function(customer) { + var customerObjectStore = db + .transaction("customers", "readwrite") + .objectStore("customers"); + customerData.forEach(function (customer) { customerObjectStore.add(customer); }); }; @@ -227,19 +239,18 @@ request.onupgradeneeded = function(event) { var request = indexedDB.open(dbName, 3); request.onupgradeneeded = function (event) { + var db = event.target.result; - var db = event.target.result; - - // 设置 autoIncrement 标志为 true 来创建一个名为 names 的对象仓库 - var objStore = db.createObjectStore("names", { autoIncrement : true }); + // 设置 autoIncrement 标志为 true 来创建一个名为 names 的对象仓库 + var objStore = db.createObjectStore("names", { autoIncrement: true }); - // 因为 names 对象仓库拥有键生成器,所以它的键会自动生成。 - // 被插入的数据可以表示如下: - // key : 1 => value : "Bill" - // key : 2 => value : "Donna" - customerData.forEach(function(customer) { - objStore.add(customer.name); - }); + // 因为 names 对象仓库拥有键生成器,所以它的键会自动生成。 + // 被插入的数据可以表示如下: + // key : 1 => value : "Bill" + // key : 2 => value : "Donna" + customerData.forEach(function (customer) { + objStore.add(customer.name); + }); }; ``` @@ -281,18 +292,18 @@ var transaction = db.transaction(["customers"], "readwrite"); ```js // 在所有数据添加完毕后的处理 -transaction.oncomplete = function(event) { +transaction.oncomplete = function (event) { alert("All done!"); }; -transaction.onerror = function(event) { +transaction.onerror = function (event) { // 不要忘记错误处理! }; var objectStore = transaction.objectStore("customers"); -customerData.forEach(function(customer) { +customerData.forEach(function (customer) { var request = objectStore.add(customer); - request.onsuccess = function(event) { + request.onsuccess = function (event) { // event.target.result === customer.ssn; }; }); @@ -305,10 +316,11 @@ customerData.forEach(function(customer) { 删除数据是非常类似的: ```js -var request = db.transaction(["customers"], "readwrite") - .objectStore("customers") - .delete("444-44-4444"); -request.onsuccess = function(event) { +var request = db + .transaction(["customers"], "readwrite") + .objectStore("customers") + .delete("444-44-4444"); +request.onsuccess = function (event) { // 删除成功! }; ``` @@ -321,10 +333,10 @@ request.onsuccess = function(event) { var transaction = db.transaction(["customers"]); var objectStore = transaction.objectStore("customers"); var request = objectStore.get("444-44-4444"); -request.onerror = function(event) { +request.onerror = function (event) { // 错误处理! }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { // 对 request.result 做些操作! alert("Name for SSN 444-44-4444 is " + request.result.name); }; @@ -333,7 +345,10 @@ request.onsuccess = function(event) { 对于一个“简单”的提取这里的代码有点多了。下面看我们怎么把它再缩短一点,假设你在数据库的级别上来进行的错误处理: ```js -db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) { +db + .transaction("customers") + .objectStore("customers") + .get("444-44-4444").onsuccess = function (event) { alert("Name for SSN 444-44-4444 is " + event.target.result.name); }; ``` @@ -350,12 +365,14 @@ db.transaction("customers").objectStore("customers").get("444-44-4444").onsucces 现在我们已经去除了一些数据,修改一下并把它插回数据库的操作时非常简单的。让我们来稍微更新一下上例中的数据。 ```js -var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers"); +var objectStore = db + .transaction(["customers"], "readwrite") + .objectStore("customers"); var request = objectStore.get("444-44-4444"); -request.onerror = function(event) { +request.onerror = function (event) { // 错误处理 }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { // 获取我们想要更新的数据 var data = event.target.result; @@ -364,12 +381,12 @@ request.onsuccess = function(event) { // 把更新过的对象放回数据库 var requestUpdate = objectStore.put(data); - requestUpdate.onerror = function(event) { - // 错误处理 - }; - requestUpdate.onsuccess = function(event) { - // 完成,数据已更新! - }; + requestUpdate.onerror = function (event) { + // 错误处理 + }; + requestUpdate.onsuccess = function (event) { + // 完成,数据已更新! + }; }; ``` @@ -384,13 +401,12 @@ request.onsuccess = function(event) { ```js var objectStore = db.transaction("customers").objectStore("customers"); -objectStore.openCursor().onsuccess = function(event) { +objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { alert("Name for SSN " + cursor.key + " is " + cursor.value.name); cursor.continue(); - } - else { + } else { alert("No more entries!"); } }; @@ -403,13 +419,12 @@ objectStore.openCursor().onsuccess = function(event) { ```js var customers = []; -objectStore.openCursor().onsuccess = function(event) { +objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { customers.push(cursor.value); cursor.continue(); - } - else { + } else { alert("以获取所有客户信息:" + customers); } }; @@ -418,7 +433,7 @@ objectStore.openCursor().onsuccess = function(event) { > **备注:** 可选地,你可以使用 `getAll()` 来处理这种情况(以及 `getAllKeys()`)。下面的代码的效果和上例相同: > > ```js -> objectStore.getAll().onsuccess = function(event) { +> objectStore.getAll().onsuccess = function (event) { > alert("Got all customers: " + event.target.result); > }; > ``` @@ -436,7 +451,7 @@ objectStore.openCursor().onsuccess = function(event) { var index = objectStore.index("name"); -index.get("Donna").onsuccess = function(event) { +index.get("Donna").onsuccess = function (event) { alert("Donna's SSN is " + event.target.result.ssn); }; ``` @@ -446,16 +461,23 @@ index.get("Donna").onsuccess = function(event) { 如果你需要访问带有给定 `name` 的所有的记录你可以使用一个游标。你可以在索引上打开两个不同类型的游标。一个常规游标映射索引属性到对象存储空间中的对象。一个键索引映射索引属性到用来存储对象存储空间中的对象的键。不同之处被展示如下: ```js -index.openCursor().onsuccess = function(event) { +index.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // cursor.key 是一个 name,就像 "Bill", 然后 cursor.value 是整个对象。 - alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email); + alert( + "Name: " + + cursor.key + + ", SSN: " + + cursor.value.ssn + + ", email: " + + cursor.value.email, + ); cursor.continue(); } }; -index.openKeyCursor().onsuccess = function(event) { +index.openKeyCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // cursor.key 是一个 name,就像 "Bill", 然后 cursor.value 是那个 SSN。 @@ -487,7 +509,7 @@ var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true); var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true); // 使用其中的一个键范围,把它作为 openCursor()/openKeyCursor 的第一个参数 -index.openCursor(boundKeyRange).onsuccess = function(event) { +index.openCursor(boundKeyRange).onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // 当匹配时进行一些操作 @@ -499,7 +521,7 @@ index.openCursor(boundKeyRange).onsuccess = function(event) { 有时候你可能想要以倒序而不是正序(所有游标的默认顺序)来遍历。切换方向是通过传递 `prev` 到 `openCursor()` 方法来实现的: ```js -objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) { +objectStore.openCursor(boundKeyRange, "prev").onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // 进行一些操作 @@ -511,7 +533,7 @@ objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) { 如果你只是想改变遍历的方向,而不想对结果进行筛选,你只需要给第一个参数传入 null。 ```js -objectStore.openCursor(null, "prev").onsuccess = function(event) { +objectStore.openCursor(null, "prev").onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the entries. @@ -523,7 +545,7 @@ objectStore.openCursor(null, "prev").onsuccess = function(event) { 因为“name”索引不是唯一的,那就有可能存在具有相同 `name` 的多条记录。要注意的是这种情况不可能发生在对象存储空间上,因为键必须永远是唯一的。如果你想要在游标在索引迭代过程中过滤出重复的,你可以传递 `nextunique` (或 `prevunique` 如果你正在向后寻找)作为方向参数。当 `nextunique` 或是 `prevunique` 被使用时,被返回的那个总是键最小的记录。 ```js -index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) { +index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the entries. @@ -541,18 +563,18 @@ index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) { ```js var openReq = mozIndexedDB.open("MyTestDatabase", 2); -openReq.onblocked = function(event) { +openReq.onblocked = function (event) { // 如果其他的一些页签加载了该数据库,在我们继续之前需要关闭它们 alert("请关闭其他由该站点打开的页签!"); }; -openReq.onupgradeneeded = function(event) { +openReq.onupgradeneeded = function (event) { // 其他的数据已经被关闭,一切就绪 db.createObjectStore(/* ... */); useDatabase(db); }; -openReq.onsuccess = function(event) { +openReq.onsuccess = function (event) { var db = event.target.result; useDatabase(db); return; @@ -561,9 +583,11 @@ openReq.onsuccess = function(event) { function useDatabase(db) { // 当由其他页签请求了版本变更时,确认添加了一个会被通知的事件处理程序。 // 这里允许其他页签来更新数据库,如果不这样做,版本升级将不会发生知道用户关闭了这些页签。 - db.onversionchange = function(event) { + db.onversionchange = function (event) { db.close(); - alert("A new version of this page is ready. Please reload or close this tab!"); + alert( + "A new version of this page is ready. Please reload or close this tab!", + ); }; // 处理数据库 @@ -624,137 +648,132 @@ Mozilla 已经在 Firefox 43+ 中实现了对 IndexedDB 数据进行地区化排 ### HTML 内容 ```html - - -

    IndexedDB Demo: storing blobs, e-publication example

    -
    -

    - Works and tested with: -

    -
    -
    -
    - -
    -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - - -
    - - - -
    - - - -
    - - - -
    - - - -
    - -
    - - -
    -
    - -
    - - - - - - - - - - - -
    - - - -
    - - - -
    -
    - - -
    -
    - -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
      -
    -
    + + +

    IndexedDB Demo: storing blobs, e-publication example

    +
    +

    Works and tested with:

    +
    +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + + +
    + + + +
    + + + +
    + +
    + + +
    +
    + +
    + + + + + + + + + + + +
    + + + +
    + + + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
      +
      ``` ### CSS 内容 @@ -852,20 +871,22 @@ input { ```js (function () { var COMPAT_ENVS = [ - ['Firefox', ">= 16.0"], - ['Google Chrome', - ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"] + ["Firefox", ">= 16.0"], + [ + "Google Chrome", + ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support", + ], ]; - var compat = $('#compat'); + var compat = $("#compat"); compat.empty(); compat.append('
        '); - COMPAT_ENVS.forEach(function(val, idx, array) { - $('#compat-list').append('
      • ' + val[0] + ': ' + val[1] + '
      • '); + COMPAT_ENVS.forEach(function (val, idx, array) { + $("#compat-list").append("
      • " + val[0] + ": " + val[1] + "
      • "); }); - const DB_NAME = 'mdn-demo-indexeddb-epublications'; + const DB_NAME = "mdn-demo-indexeddb-epublications"; const DB_VERSION = 1; // Use a long long for this value (don't use a float) - const DB_STORE_NAME = 'publications'; + const DB_STORE_NAME = "publications"; var db; @@ -888,12 +909,14 @@ input { req.onupgradeneeded = function (evt) { console.log("openDb.onupgradeneeded"); - var store = evt.currentTarget.result.createObjectStore( - DB_STORE_NAME, { keyPath: 'id', autoIncrement: true }); - - store.createIndex('biblioid', 'biblioid', { unique: true }); - store.createIndex('title', 'title', { unique: false }); - store.createIndex('year', 'year', { unique: false }); + var store = evt.currentTarget.result.createObjectStore(DB_STORE_NAME, { + keyPath: "id", + autoIncrement: true, + }); + + store.createIndex("biblioid", "biblioid", { unique: true }); + store.createIndex("title", "title", { unique: false }); + store.createIndex("year", "year", { unique: false }); }; } @@ -907,9 +930,9 @@ input { } function clearObjectStore(store_name) { - var store = getObjectStore(DB_STORE_NAME, 'readwrite'); + var store = getObjectStore(DB_STORE_NAME, "readwrite"); var req = store.clear(); - req.onsuccess = function(evt) { + req.onsuccess = function (evt) { displayActionSuccess("Store cleared"); displayPubList(store); }; @@ -921,10 +944,9 @@ input { function getBlob(key, store, success_callback) { var req = store.get(key); - req.onsuccess = function(evt) { + req.onsuccess = function (evt) { var value = evt.target.result; - if (value) - success_callback(value.blob); + if (value) success_callback(value.blob); }; } @@ -934,12 +956,12 @@ input { function displayPubList(store) { console.log("displayPubList"); - if (typeof store == 'undefined') - store = getObjectStore(DB_STORE_NAME, 'readonly'); + if (typeof store == "undefined") + store = getObjectStore(DB_STORE_NAME, "readonly"); - var pub_msg = $('#pub-msg'); + var pub_msg = $("#pub-msg"); pub_msg.empty(); - var pub_list = $('#pub-list'); + var pub_list = $("#pub-list"); pub_list.empty(); // Resetting the iframe so that it doesn't display previous content newViewerFrame(); @@ -950,18 +972,21 @@ input { // transaction, and their results are returned in the same order. // Thus the count text below will be displayed before the actual pub list // (not that it is algorithmically important in this case). - req.onsuccess = function(evt) { - pub_msg.append('

        There are ' + evt.target.result + - ' record(s) in the object store.

        '); + req.onsuccess = function (evt) { + pub_msg.append( + "

        There are " + + evt.target.result + + " record(s) in the object store.

        ", + ); }; - req.onerror = function(evt) { + req.onerror = function (evt) { console.error("add error", this.error); displayActionFailure(this.error); }; var i = 0; req = store.openCursor(); - req.onsuccess = function(evt) { + req.onsuccess = function (evt) { var cursor = evt.target.result; // If the cursor is pointing at something, ask for the data @@ -970,21 +995,31 @@ input { req = store.get(cursor.key); req.onsuccess = function (evt) { var value = evt.target.result; - var list_item = $('
      • ' + - '[' + cursor.key + '] ' + - '(biblioid: ' + value.biblioid + ') ' + - value.title + - '
      • '); - if (value.year != null) - list_item.append(' - ' + value.year); - - if (value.hasOwnProperty('blob') && - typeof value.blob != 'undefined') { + var list_item = $( + "
      • " + + "[" + + cursor.key + + "] " + + "(biblioid: " + + value.biblioid + + ") " + + value.title + + "
      • ", + ); + if (value.year != null) list_item.append(" - " + value.year); + + if ( + value.hasOwnProperty("blob") && + typeof value.blob != "undefined" + ) { var link = $('File'); - link.on('click', function() { return false; }); - link.on('mouseenter', function(evt) { - setInViewer(evt.target.getAttribute('href')); }); - list_item.append(' / '); + link.on("click", function () { + return false; + }); + link.on("mouseenter", function (evt) { + setInViewer(evt.target.getAttribute("href")); + }); + list_item.append(" / "); list_item.append(link); } else { list_item.append(" / No attached file"); @@ -1004,9 +1039,9 @@ input { } function newViewerFrame() { - var viewer = $('#pub-viewer'); + var viewer = $("#pub-viewer"); viewer.empty(); - var iframe = $('