사용자가 select 태그에서 상위 카테고리의 값을 선택할 때마다
하위 카테고리의 목록이 바뀌도록 이벤트를 주려고 한다.
select 태그가 갖는 onchange라는 요소를 추가하려고 했다.
하지만 값이 함수로 안 가고 문자열로 바뀌어서 들어갔다.
let testch = function() {
alert('change1');
}
let sel = document.querySelector('#sales_type');
sel.setAttribute('onchange', testch);
//결과
<select id="sales_type" onchange="function() {
alert('change1');
}">
함수를 직접 주지 않고, 함수 이름만 전달하기로 했다.
그러면 그 이름을 갖는 함수를 script에서 찾아서 실행할 것이다.
아래처럼 하니 정상적으로 함수가 실행됐다.
let sel = document.querySelector('#sales_type');
let testch = function() {
alert('change1');
}
sel.setAttribute('onchange', "testch()");
//결과
<select id="sales_type" onchange="testch()">
아래와 같이 객체처럼 접근해서 직접 지정해 줄 수도 있다.
이렇게 하면 select 태그 자체에는 변화가 없다.
다만 해당 select 의 Event Listener 안을 들여다 보면
change 이벤트에 우리가 넣어 준 함수가 들어 있는 것을 알 수 있다.
let testch = function() {
alert('change1');
}
let sel = document.querySelector('#sales_type');
sel.onchange = testch;
//위와 아래는 같은 내용
let sel = document.querySelector('#sales_type');
sel.onchange = function() {
alert('change2');
};
//결과
<select id="sales_type">
javaScript의 addEventListener 함수를 이용해도 된다.
let sel = document.querySelector('#sales_type');
sel.addEventListener('change', testch);
//위와 아래는 같은 내용
document.querySelector('#sales_type').addEventListener('change', function() {
alert('change2');
});
220401
참고 자료
https://developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener
반응형
'JavaScript' 카테고리의 다른 글
| JavaScript로 select 태그에 option 요소들 나중에 추가하기 (appendChild) (0) | 2022.04.02 |
|---|---|
| <select> 태그 안에서 선택된 <option> 값 가져오기 (options.selectedIndex) (0) | 2022.04.02 |
| JavaScript 이벤트 객체란? 구조와 내용, 속성 값 꺼내 오기 (0) | 2022.04.02 |
| 나중에 추가한 자식 요소에 이벤트 추가하기 (delegated event) (0) | 2022.04.02 |
| 여러 계층에 걸쳐서 자식 요소를 선택하는 방법 jQuery 선택자 (0) | 2022.04.02 |