JavaScript (DOM)
54543 ワード
イベントオカレンスオブジェクト
これまで,アクティビティ内で文書オブジェクト変数を用いて文書オブジェクトに関する情報を抽出してきた.
document.addEventListener('DOMContentLoaded', () => {
const textarea = document.querySelector('textarea')
const h1 = document.querySelector('h1')
textarea.addEventListener('keyup', (event) => {
const length = textarea.value.length
h1.textContent = `글자 수 : ${length}`
})
})
ただし、イベントリスナー内ではこれらの変数にアクセスできない場合があります.イベントリスナーを削除
const listener = (event) => {
const length = textarea.value.length
// 현재 블록에서는 textarea 변수를 사용불가
h1.textContent = `글자 수 : ${length}`
}
document.addEventListener('DOMContentLoaded', () => { // 이벤트 리스너가 외부로 분리
const textarea = document.querySelector('textarea')
const h1 = document.querySelector('h1')
textarea.addEventListener('keyup', (event))
})
コードの規模が大きいほど、イベントリスナーは隔離されやすくなります.この場合、励起イベントのオブジェクト(現在のコードのtextarea)には、次のようにアクセスできます.2つの方法があります
event.currentTargetプロパティの使用
どちらの形状でも使用できます()
このキーワードを使用
矢印関数ではなく関数(){}として関数を宣言する場合に使用します.
const listener = (event) => {
const length = event.currentTarget.value.length
// event.currentTarget 가 textarea가 된다.
h1.textContent = `글자수 : ${length}`
}
const textarea = document.querySelector('textarea')
const h1 = document.querySelector('h1')
textarea.addEventListener('keyup', listener)
実行時このキーワードを使用する場合
const listener = function (event) {
const length = this.value.length
h1.textContent = `글자수 : ${length}`
}
const textarea = document.querySelector('textarea')
const h1 = document.querySelector('h1')
textarea.addEventListener('keyup', listener)
実行時テキスト入力フォームイベント
ユーザー入力を受信するときに使用する要素を入力フォームと呼びます.HTMLではinputタグ、textareaタグ、buttonタグ、selectタグなどが入力形式です.
入力フォームを使用する簡単な例
インチをセンチメートルに変換するプログラム
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('input')
const btn = document.querySelector('button')
const p = document.querySelector('p')
btn.addEventListener('click', () => {
// 입력을 숫자로 변환
const inch = parseInt(input.value)
if(isNaN(inch)) {
p.textContent = `'${input.value}'는 숫자가 아닙니다.`
return
}
const cm = inch * 2.54
p.textContent = `${cm} cm`
})
})
<input type="text"/> inch
<button>계산</button>
<p></p>
実行数値を入力
ハングルを入力
検証の例
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('input')
const p = document.querySelector('p')
const isEmail = (value) => {
// @를 가지고 있고 && @ 뒤에 . 이 있다면
// Email인지 검사하는 함수
return (value.indexOf('@') > 1) && (value.split('@')[1].indexOf('.') > 1)
}
input.addEventListener('keyup', (event) => {
const value = event.currentTarget.value
if(isEmail(value)) {
p.style.color = 'green'
p.textContent = `이메일 형식입니다. : ${value}`
} else {
p.style.color = 'red'
p.textContent = `이메일 형식이 아닙니다. : ${value}`
}
})
})
<input type="text">
<p></p>
実行結果エラーの場合
正しい状況
まず簡単な形でメール形式を区別しました.
通常、この検証では正規表現が使用されます.
ドロップダウン・リストの使用
デフォルトでは、ドロップダウンリストはselectタグで実装されます.
selectタグを使用してドロップダウンリストを作成し、選択ドロップダウンリストを印刷する場合(値の変更)選択するオプション
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('select')
const span = document.querySelector('span')
span.style.color = 'red'
span.style.fontWeight = 'bold'
select.addEventListener('change', (event) => {
const options = event.currentTarget.options
const index = event.currentTarget.options.selectedIndex
span.textContent = options[index].textContent
// 선택한 option 태그를 추출한다.
})
})
<select>
<option>떡볶이</option>
<option>순대</option>
<option>튀김</option>
<option>오뎅</option>
</select>
<p>선택 : <span>떡볶이</span></p>
<!-- 처음에 떡볶이가 선택되어 있도록 초깃값을 지정 -->
実行時もしあなたが他のものを選んだら
コードを実行してドロップダウン・リストからアイテムを選択すると、オプション「索引」から選択したオプション・ラベルが出力されます.現在のコードはtextContentプロパティを直接抽出して使用しており、optionラベルに他のプロパティを付与して使用できます.
※ここに文字スタイルの変更アクティビティを入力
元の入力フォームで値変更時にchangeイベントが発生します.文字入力フォームは、入力フォーム(フォーカス状態)を選択して文字を入力し、選択解除(ブラー状態)時に変更イベントが発生します.したがって、ユーザ入力中に変更イベントは発生しません.
selectタグに複数のプロパティを割り当てると、ctrlキーまたはShiftキーを押して複数のアイテムを選択できる選択ボックスが表示されます.このmultipleselectラベルの使用方法は少し特殊です.
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('select')
const span = document.querySelector('span')
span.style.color = 'red'
span.style.fontWeight = 'bold'
select.addEventListener('change', (event) => {
const options = event.currentTarget.options
const list = []
for (const option of options) {
if (option.selected) {
list.push(option.textContent)
}
}
span.textContent = list.join(', ')
})
})
<select multiple>
<option>떡볶이</option>
<option>순대</option>
<option>튀김</option>
<option>오뎅</option>
</select>
<p>선택 : <span></span></p>
実行時二つを選ぶと.
こうして出てきた
センチメートル単位を複数単位に変換するプログラムの例
document.addEventListener('DOMContentLoaded', () => {
// 현재값
let now
// 변환 상수
let change = 10
const input = document.querySelector('input')
const span = document.querySelector('span')
const select = document.querySelector('select')
const calculate = () => {
span.textContent = (now * change).toFixed(2) // 소수점 2번째 자리까지 출력
// toFixed() 메소드는 숫자를 문자열로 변환
}
select.addEventListener('change', (event) => {
const options = event.currentTarget.options
const index = event.currentTarget.options.selectedIndex
change = Number(options[index].value)
// 항목을 선택하면 항목의 value 속성을 추출
calculate()
})
input.addEventListener('keyup', (event) => {
now = Number(event.currentTarget.value)
// 값을 입력하면 현재 값을 추출
calculate()
})
})
<input type="text"> cm =
<span></span>
<br/>
<select>
<option value="10">mm</option>
<option value="0.01">m</option>
<option value="0.393701">inch</option>
</select>
実行時数字を入力すると、
ドロップダウン・メニューをクリックします
インチに変更
練習にする.
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('#select')
const input = document.querySelector('#input')
const btn = document.querySelector('button')
const output = document.querySelector('#output')
const p = document.querySelector('p')
const span = document.querySelector('span')
let now;
let change = 10
const cal = () => {
output.value = (now * change).toFixed(2)
p.textContent = `${input.value} cm 는 ${output.value} mm 입니다.`
}
select.addEventListener('change', (event) => {
const options = event.currentTarget.options
const index = event.currentTarget.options.selectedIndex
change = Number(options[index].value)
span.textContent = options[index].textContent
cal()
p.textContent = `${input.value} cm 는 ${output.value} ${options[index].textContent} 입니다.`
})
input.addEventListener('keyup', (event) => {
now = Number(event.currentTarget.value)
cal()
})
})
<select id="select">
<option value="10">mm</option>
<option value="0.01">m</option>
<option value="0.393701">inch</option>
</select>
<input id="input" type="text"> cm
<button>입력</button>
<input id="output" type="text" disabled>
<span>mm</span>
<p></p>
実行時数字を入力すると、
下端同時出力.
ドロップダウン・メニューをクリックします.
mに変えると.
実は入力ボタンは必要ありません.修正する必要があります.
Reference
この問題について(JavaScript (DOM)), 我々は、より多くの情報をここで見つけました https://velog.io/@dohy9443/JavaScript-DOM-dx1kft4vテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol