커뮤니티

고용노동부, 산업인력공단과 함께하는 강원도 유일한 기업중심 IT전문교육기관 ICT융합캠퍼스만의 특별한교육입니다.
공인 IT숙련기술인의 다양한 접근방법으로 전문가다운 실무교육을 받을 수 있습니다.

Category

교육강좌

클라이언트 웹브라우저 자바스크립트 - 기본동작의 취소

페이지 정보

작성자 관리자 댓글 0건 조회 2,422회 작성일 20-07-20 14:35

본문

기본동작의 취소

웹브라우저의 구성요소들은 각각 기본적인 동작 방법을 가지고 있다.

  • 텍스트 필드에 포커스를 준 상태에서 키보드를 입력하면 텍스트가 입력된다.
  • 폼에서 submit 버튼을 누르면 데이터가 전송된다.
  • a 태그를 클릭하면 href 속성의 URL로 이동한다.

이러한 기본적인 동작들을 기본 이벤트라고 하는데 사용자가 만든 이벤트를 이용해서 이러한 기본 동작을 취소할 수 있다.

inline

이벤트의 리턴값이 false이면 기본 동작이 취소된다.

1
2
3
4
5
6
7
8
9
10
11
<p>
<label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />
</p>
<p>
<a href="http://opentutorials.org" onclick="if(document.getElementById('prevent').checked) return false;">opentutorials</a>
</p>
<p>
<form action="http://opentutorials.org" onsubmit="if(document.getElementById('prevent').checked) return false;">
<input type="submit" />
</form>
</p>

property 방식

리턴 값이 false이면 기본동작이 취소된다. (실행)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<p>
<label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />
</p>
<p>
<a href="http://opentutorials.org">opentutorials</a>
</p>
<p>
<form action="http://opentutorials.org">
<input type="submit" />
</form>
</p>
<script>
document.querySelector('a').onclick = function(event){
if(document.getElementById('prevent').checked)
return false;
};
document.querySelector('form').onclick = function(event){
if(document.getElementById('prevent').checked)
return false;
};
</script>

addEventListener 방식

이 방식에서는 이벤트 객체의 preventDefault 메소드를 실행하면 기본 동작이 취소된다. (실행)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<p>
<label>prevent event on</label><input id="prevent" type="checkbox" name="eventprevent" value="on" />
</p>
<p>
<a href="http://opentutorials.org">opentutorials</a>
</p>
<p>
<form action="http://opentutorials.org">
<input type="submit" />
</form>
</p>
<script>
document.querySelector('a').addEventListener('click', function(event){
if(document.getElementById('prevent').checked)
event.preventDefault();
});
document.querySelector('form').addEventListener('submit', function(event){
if(document.getElementById('prevent').checked)
event.preventDefault();
});
</script>
ie9 이하 버전에서는 event.returnValue를 false로 해야 한다. 

 

  • 트위터로 보내기
  • 페이스북으로 보내기
  • 구글플러스로 보내기

답변목록

등록된 답변이 없습니다.