Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Modifying the document#494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 7 commits intojavascript-tutorial:masterfromjoaquinelio:modidocu
Jul 31, 2021
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
Answer: **1and 3**.
Respuesta: **1y 3**.

Both commands result in adding the`text` "as text" into the `elem`.
Ambos comandos agregan`text` "como texto" dentro de `elem`.

Here's an example:
Aquí el ejemplo:

```html run height=80
<div id="elem1"></div>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,9 +4,9 @@ importance: 5

# createTextNode vs innerHTML vs textContent

We have an emptyDOMelement `elem`and a string `text`.
Tenemos un elementoDOMvacio `elem`y un string `text`.

Which of these 3commands will do exactly the same?
¿Cuáles de estos 3comandos harán exactamente lo mismo?

1. `elem.append(document.createTextNode(text))`
2. `elem.innerHTML = text`
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
First, let's make HTML/CSS.
Primero escribamos HTML/CSS.

Each component of the time would look great in its own `<span>`:
Cada componente de la hora se verá muy bien dentro de su propio `<span>`:

```html
<div id="clock">
<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div>
```

Also we'll needCSSto color them.
También necesitamosCSSpara colorearlos.

The`update`function will refresh the clock, to be called by`setInterval`every second:
La función`update`que refrescará el reloj será llamada por`setInterval`una vez por segundo:

```js
function update() {
Expand All@@ -32,15 +32,15 @@ function update() {
}
```

In the line `(*)`we every time check the current date. The calls to `setInterval`are not reliable: they may happen with delays.
En la línea `(*)`verificamos la hora cada vez. Las llamadas a `setInterval`no son confiables: pueden ocurrir con demoras.

The clock-managing functions:
Las funciones que manejan el reloj:

```js
let timerId;

function clockStart() { //run the clock
if (!timerId) { //only set a new interval if the clock is not running
function clockStart() { //ejecuta el reloj
if (!timerId) { //solo establece un nuevo intervalo si el reloj no está corriendo
timerId = setInterval(update, 1000);
}
update(); // (*)
Expand All@@ -52,6 +52,6 @@ function clockStop() {
}
```

Please note that the call to`update()`is not only scheduled in `clockStart()`,but immediately run in the line`(*)`.Otherwise the visitor would have to wait till the first execution of`setInterval`.And the clock would be empty till then.
Nota que la llamada a`update()`no solo está agendada en `clockStart()`,también la ejecuta inmediatamente en la línea`(*)`.De otro modo el visitante tendría que esperar hasta la primera ejecución de`setInterval`.Y el reloj estaría vacío hasta entonces.

Also it is important to set a new interval in`clockStart()`only when the clock is not running. Otherways clicking the start button several times would set multiple concurrent intervals. Even worse - we would only keep the`timerID`of the last interval, losing references to all others. Then we wouldn't be able to stop the clock ever again! Note that we need to clear the`timerID`when the clock is stopped in the line `(**)`,so that it can be started again by running `clockStart()`.
También es importante establecer un nuevo intervalo en`clockStart()`solamente cuando el reloj no está corriendo. De otra forma al cliquear el botón de inicio varias veces se establecerían múltiples intervalos concurrentes. Peor aún, solo mantendríamos el`timerID`del último intervalo, perdiendo referencia a todos los demás. ¡No podríamos detener el reloj nunca más! Nota que necesitamos limpiar`timerID`cuando el reloj es detenido en la línea `(**)`,así puede ser reiniciado corriendo `clockStart()`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,26 +43,26 @@
}

function clockStart() {
//set a new interval only if the clock is stopped
//otherwise we would rewrite thetimerIDreference to the running interval and wouldn't be able to stop the clock ever again
//establece un nuevo intervalo solo si el reloj está detenido
//de otro modo sobreescribiríamos la referenciatimerIDdel intervalo en ejecución y no podríamos detener el reloj nunca más
if (!timerId) {
timerId = setInterval(update, 1000);
}
update(); // <--start right now, don't wait 1 secondtill the first setInterval works
update(); // <--inicia ahora mismo, no espera 1 secondhasta el primer intervalo
}

function clockStop() {
clearInterval(timerId);
timerId = null; // <--clear timerIDto indicate that the clock has been stopped, so that it is possible to start it again in clockStart()
timerId = null; // <--borra timerIDpara indicar que el reloj fue detenido, haciendo posible iniciarlo de nuevo en clockStart()
}

clockStart();
</script>

<!--click on this button calls clockStart() -->
<!--cliquear este botón llama a clockStart() -->
<input type="button" onclick="clockStart()" value="Start">

<!--click on this button calls clockStop() -->
<!--cliquear este botón llama a clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">

</body>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,10 +2,10 @@
<html>
<body>

<!--click on this button calls clockStart() -->
<!--cliquear en este botón llama a clockStart() -->
<input type="button" onclick="clockStart()" value="Start">

<!--click on this button calls clockStop() -->
<!--cliquear en este botón llama a clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">

</body>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,10 +2,10 @@ importance: 4

---

#Colored clock with setInterval
#Reloj coloreado con setInterval

Create a colored clock like here:
Crea un reloj coloreado como aquí:

[iframe src="solution" height=60]

Use HTML/CSSfor the styling, JavaScriptonly updates time in elements.
Usa HTML/CSSpara el estilo, JavaScriptsolamente actualiza la hora en elements.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@

When we need to insert a piece of HTML somewhere, `insertAdjacentHTML`is the best fit.
Cuando necesitamos insertar una pieza de HTML en algún lugar, `insertAdjacentHTML`es lo más adecuado.

The solution:
La solución:

```js
one.insertAdjacentHTML('afterend', '<li>2</li><li>3</li>');
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 5

---

#Insert theHTMLin the list
#Inserta elHTMLen la lista

Write the code to insert`<li>2</li><li>3</li>`between two `<li>`here:
Escribe el código para insertar`<li>2</li><li>3</li>`entre dos `<li>`aquí:

```html
<ul id="ul">
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
The solution is short, yet may look a bit tricky, so here I provide it with extensive comments:
La solución es corta, pero puede verse algo dificultosa así que brindamos comentarios extendidos:

```js
let sortedRows = Array.from(table.tBodies[0].rows) // 1
Expand All@@ -7,12 +7,12 @@ let sortedRows = Array.from(table.tBodies[0].rows) // 1
table.tBodies[0].append(...sortedRows); // (3)
```

The step-by-step algorthm:
El algoritmo paso a paso:

1.Get all`<tr>`, from `<tbody>`.
2.Then sort them comparing by the content of the first`<td>` (the name field).
3.Now insert nodes in the right order by `.append(...sortedRows)`.
1.Obtener todos los`<tr>` de `<tbody>`.
2.Entonces ordenarlos comparando por el contenido de su primer`<td>` (el campo nombre).
3.Ahora insertar nodos en el orden correcto con `.append(...sortedRows)`.

We don't have to remove row elements, just "re-insert",they leave the old place automatically.
No necesitamos quitar los elementos row, simplemente "reinsertarlos",ellos dejan el viejo lugar automáticamente.

P.S.In our case, there's an explicit`<tbody>`in the table, but even if HTML table doesn't have`<tbody>`,theDOMstructure always has it.
P.S.En nuestro caso, hay un`<tbody>`explícito en la tabla, pero incluso si la tabla HTML no tiene`<tbody>`,la estructuraDOMsiempre lo tiene.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,5 +23,5 @@
</table>

<script>
// ...your code ...
// ...tu código ...
</script>
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 5

---

#Sort the table
#Ordena la tabla

There's a table:
Tenemos una tabla:

```html run
<table>
Expand All@@ -30,6 +30,6 @@ There's a table:
</table>
```

There may be more rows in it.
Puede haber más filas en ella.

Write the code to sort it by the `"name"` column.
Escribe el código para ordenarla por la columna `"name"`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@

First, let's see how *not* to do it:
Primero veamos cómo *no* hacerlo:

```js
function clear(elem) {
Expand All@@ -9,11 +9,11 @@ function clear(elem) {
}
```

That won't work, because the call to `remove()`shifts the collection `elem.childNodes`,so elements start from the index`0`every time. But `i`increases, and some elements will be skipped.
Eso no funciona, porque la llamada a `remove()`desplaza la colección `elem.childNodes`,entonces los elementos comienzan desde el índice`0`cada vez. Pero `i`se incrementa y algunos elementos serán saltados.

The`for..of`loop also does the same.
El bucle`for..of`también hace lo mismo.

The right variant could be:
Una variante correcta puede ser:

```js
function clear(elem) {
Expand All@@ -23,7 +23,7 @@ function clear(elem) {
}
```

And also there's a simpler way to do the same:
Y también una manera más simple de hacer lo mismo:

```js
function clear(elem) {
Expand Down
12 changes: 6 additions & 6 deletions2-ui/1-document/07-modifying-document/4-clear-elem/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,19 +2,19 @@ importance: 5

---

#Clear the element
#Limpiar el elemento

Create a function `clear(elem)`that removes everything from the element.
Crea una función `clear(elem)`que remueva todo del elemento.

```html run height=60
<ol id="elem">
<li>Hello</li>
<li>World</li>
<li>Hola</li>
<li>mundo</li>
</ol>

<script>
function clear(elem) { /*your code */ }
function clear(elem) { /*tu código */ }

clear(elem); //clears the list
clear(elem); //borra la lista
</script>
```
10 changes: 5 additions & 5 deletions2-ui/1-document/07-modifying-document/5-why-aaa/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
The HTMLin the task is incorrect. That's the reason of the odd thing.
El HTMLde la tarea es incorrecto. Esa es la razón del comportamiento extraño.

The browser has to fix it automatically. But there may be no text inside the`<table>`:according to the spec only table-specific tags are allowed. So the browser shows `"aaa"` *before* the `<table>`.
El navegador tiene que corregirlo automáticamente. No debe haber texto dentro de`<table>`:de acuerdo con la especificación solo son permitidas las etiquetas específicas de tabla. Entonces el navegador ubica `"aaa"` *antes* de `<table>`.

Now it's obvious that when we remove the table, it remains.
Ahora resulta obvio que cuando quitamos la tabla, ese texto permanece.

The question can be easily answered by exploring theDOMusing the browser tools. You'll see `"aaa"`before the `<table>`.
La pregunta puede ser respondida fácilmente explorando elDOMusando la herramientas del navegador. Estas muestran `"aaa"`antes que `<table>`.

TheHTMLstandard specifies in detail how to process badHTML, and such behavior of the browser is correct.
El estándarHTMLespecifica en detalle cómo procesarHTML incorrecto, y tal comportamiento del navegador es el correcto.
12 changes: 6 additions & 6 deletions2-ui/1-document/07-modifying-document/5-why-aaa/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,13 +2,13 @@ importance: 1

---

#Why does "aaa"remain?
#Por qué "aaa"permanece?

In the example below, the call `table.remove()`removes the table from the document.
En el ejemplo de abajo, la llamada `table.remove()`quita la tabla del documento.

But if you run it, you can see that the text `"aaa"`is still visible.
Pero si la ejecutas, puedes ver que el texto"aaa"`es aún visible.

Why does that happen?
¿Por qué ocurre esto?

```html height=100 run
<table id="table">
Expand All@@ -19,9 +19,9 @@ Why does that happen?
</table>

<script>
alert(table); //the table, as it should be
alert(table); //la tabla, tal como debería ser

table.remove();
//why there's stillaaain the document?
//¿Por qué aún estáaaaen el documento?
</script>
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
Please note the usage of`textContent`to assign the`<li>` content.
Observa el uso de`textContent`para asignar el contenido de`<li>`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
<!DOCTYPE HTML>
<html>
<body>
<h1>Create a list</h1>
<h1>Crear un lista</h1>

<script>
let ul = document.createElement('ul');
document.body.append(ul);

while (true) {
let data = prompt("Enter the text for the list item", "");
let data = prompt("Ingresa el texto para el ítem de la lista", "");

if (!data) {
break;
Expand Down
16 changes: 8 additions & 8 deletions2-ui/1-document/07-modifying-document/6-create-list/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,18 +2,18 @@ importance: 4

---

#Create a list
#Crear una lista

Write an interface to create a list from user input.
Escribir una interfaz para crear una lista de lo que ingresa un usuario.

For every listitem:
Para cadaitem de la lista:

1.Ask a user about its content using `prompt`.
2.Create the `<li>`with it and add it to `<ul>`.
3.Continue until the user cancels the input (by pressing`key:Esc`or via an empty entry).
1.Preguntar al usuario acerca del contenido usando `prompt`.
2.Crear el `<li>`con ello y agregarlo a `<ul>`.
3.Continuar hasta que el usuario cancela el ingreso (presionando`key:Esc`o con un ingreso vacío).

All elements should be created dynamically.
Todos los elementos deben ser creados dinámicamente.

If a user typesHTML-tags, they should be treated like a text.
Si el usuario ingresa etiquetasHTML, deben ser tratadas como texto.

[demo src="solution"]
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,8 +28,8 @@
}

function createTreeDom(obj) {
//if there'snochildren, then the call returns undefined
//and the <ul>won't be created
//sinotiene hijos, el llamado devuelve undefined
//y el <ul>no será creado
if (!Object.keys(obj).length) return;

let ul = document.createElement('ul');
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,7 +27,7 @@
container.innerHTML = createTreeText(obj);
}

function createTreeText(obj) { //standalone recursive function
function createTreeText(obj) { //función recursiva aislada
let li = '';
let ul;
for (let key in obj) {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
The easiest way to walk the object is to use recursion.
La forma más fácil de recorrer el objeto es usando recursividad.

1. [The solution with innerHTML](sandbox:innerhtml).
2. [The solution with DOM](sandbox:build-tree-dom).
1. [La solución con innerHTML](sandbox:innerhtml).
2. [La solución con DOM](sandbox:build-tree-dom).
Loading

[8]ページ先頭

©2009-2025 Movatter.jp