3.자바스크립트/JavaScript

열기, 닫기 클릭 시 div 보였다 안보였다 하게 하기


HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div class="guideBox">
  <p>검색조건<span class="textbtn">[열기]</span></p>
  <div style="display:none">
 
    <div>
      <dl>
        <dd>
          <select id="a" name="a">
            <option value="a1">A1</option>
            <option value="a2">A2</option>
            <option value="a3">A3</option>
          </select>
        </dd>
      </dl>
    </div>
 
  </div>
</div>
cs


Script
1
2
3
4
5
6
7
8
9
$(document).on("click",".guideBox > p",function(){
      if($(this).next().css("display")=="none"){
        $(this).next().show();
        $(this).children("span").text("[닫기]");
      }else{
        $(this).next().hide();
        $(this).children("span").text("[열기]");
      }
});
cs


테이블 tr, td 등 선택하기



<원본테이블>


▼위 원본 테이블 그리는 html 소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<table summary="연립다세대 실거래가조회 결과입니다." id="rh_table" style="display: none;">                                         
    <caption>연립다세대 실거래가조회 목록 안내</caption>                                                                                                  
    <colgroup>                                                                                                                             
        <col width='*'>                                                                                                                    
        <col width='15%'>                                                                                                                  
        <col width='10%'>                                                                                                                  
        <col width='12%'>                                                                                                                  
        <col width='12%'>                                                                                                                  
        <col width='10%'>                                                                                                                  
        <col width='15%'>                                                                                                                  
        <col width='5%'>                                                                                                                   
        <col width='8%'>                                                                                                                   
    </colgroup>                                                                                                                            
    <thead>                                                                                                                                
        <tr>                                                                                                                               
            <th scope='col' rowspan='2'>단지</th>                                                                                            
            <th scope='col' rowspan='2'>법정동</th>                                                                                           
            <th scope='col' rowspan='2'>지번</th>                                                                                            
            <th scope='col' rowspan='2'>전용<br/>면적(㎡)</th>                                                                                  
            <th scope='col' rowspan='2'>대지권<br/>면적(㎡)</th>                                                                                 
            <th scope='col' colspan='3'><span class="searchYearMonth"><fmt:formatDate value="${dateTime}" pattern="yyyy년 M월"/></span></th
            <th scope='col' rowspan='2'>건축<br/>년도</th>                                                                                     
        </tr>                                                                                                                              
        <tr>                                                                                                                               
            <th scope='col'>계약일</th>                                                                                                       
            <th scope='col'>거래금액(만원)</th>                                                                                                  
            <th scope='col'>층</th>                                                                                                         
        </tr>                                                                                                                              
    </thead>                                                                                                                               
    <tbody>                                                                                                                                
        <tr>                                                                                                                               
            <td colspan='9'>검색결과가 없습니다.</td>                                                                                               
        </tr>                                                                                                                              
    </tbody>                                                                                                                               
</table>                                                                                                                                   
cs



그런데 표 자체는 그대로 두면서 

thead-tr-th 안의 글자를 바꾼다던가

thead-tr-th 추가 또는 삭제를 해서 테이블을 가공하고 싶을 때.



<가공된 테이블>


▼ 위 가공된 테이블처럼 원본테이블을 조작하려면

1
2
3
4
5
if ("대지권면적(㎡)" == $("#rh_table > thead > tr:nth-child(1) > th:nth-child(5)").text()) {   
    $("#rh_table > thead > tr:nth-child(2) > th:nth-child(2)").html("보증금<br/>월세");       
                                                                                         
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(5)").remove();                 
}                                                                                        
cs

thead 가 2줄인데 첫번째 tr에서 다섯번째 th 텍스트가 대지권면적인지?

맞다면 테이블 가공해야하므로 if문 안의 내용을 실행.

아니라면 테이블이 이미 가공된 상태이므로 if문 패스.


if문 안의 내용은

thead에서 두번째 tr을 찾아서 그 tr의 2번째 th를 찾아 거래금액(만원)을 보증금월세로 바꾸고.

대지권면적 th를 제거.



가공된 테이블을 다시 원본테이블로 바꾸려면?

1
2
3
4
5
6
7
8
9
if ("대지권면적(㎡)" != $("#rh_table > thead > tr:nth-child(1) > th:nth-child(5)").text()) {        
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(1)").html("법정동");                   
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(2)").html("지번");                    
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(3)").html("전용<br/>면적(㎡)");          
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(4)").html("대지권<br/>면적(㎡)");         
    $("#rh_table > thead > tr:nth-child(2) > th:nth-child(2)").html("거래금액(만원)");              
                                                                                              
    $("#rh_table > thead > tr:nth-child(1)").prepend("<th schope='col' rowspan='2'>단지</th>"); 
}                                                                                             
cs

thead > 첫번째 tr> 다섯번째 th 의 텍스트가 대지권면적이 아니면 if문 안의 내용을 실행.

append()는 뒤에 붙이는거고, prepend()는 앞에 붙이는건데 prepend() 이걸 쓰는 이유는

rowspan 이 없으면 th 위치를 지정할 수 있을 것 같은데

rowspan 대문에 th 위치 지정해서 th 추가하기가 쉽지 않아서..

th 텍스트를 바꿔주고 제일 앞에 th를 추가해주는 식으로 함.


커서치면 아래에 뜨게 하기




<HTML>

1
2
3
4
5
6
7
8
<div class="col-sm-10">
    <div class="col-sm-12">
        <input type="hidden" name="memCode" id="memCode"/>
        <input type="hidden" name="value-keyword" id="value-keyword"/>
        <input type="hidden" name="str" id="str"/>
        <input type="text" class="col-xs-10 col-sm-10" id="memName" name="memName" autocomplete="off" placeholder="회원이름">
    </div>
</div>
cs





아래 스크립트는 .keyup(), .keypress(), .autocomplete() 을 활용한 내용.


참고한 사이트:

http://findfun.tistory.com/284

http://blog.naver.com/junhwen/130158515885

http://javafactory.tistory.com/entry/jQueryEventkeydownkeypresskeyup-%ED%82%A4%EB%B3%B4%EB%93%9C-%EC%9D%B4%EB%B2%A4%ED%8A%B8


.keyup()

키보드를 누르고 있다가 뗄 떼 이벤트 발생

누른 키가 뭔지 확인하려면 event 객체 활용

브라우저가 event 객체 정보를 가지고 있으면 jQuery의 .which 속성을 사용해 키보드 키 활인 가능

예) event.which = 13 은 엔터키

실제 텍스트를 잡아내려면 .keyup() 보다는 .keypress()를 사용

영어는 .keypress() 이벤트 사용 가능하지만 한글은 지원하지 않아 .keyup() 사용해야 한다


.keypress()

키보드가 입력 받았을 때 이벤트 발생

키 누름을 감지할 필요가 있을 때

.keydown() 와 비슷하지만 키를 반복적으로 누를 때 다름

키를 계속 누르고 있다면 .keydown() 은 이벤트 한 번 발생, .keypress() 는 문자 찍힐 때마다 이벤트 발생

보조키(shift) 누르면 .keydown() 은 이벤트 발생, .keypress() 는 이벤트 발생하지 않음.

그러나 .keypress() 는 공식적으로 지원하지 않는 함수. 브라우저별, 브라우저 버전별, 플랫폼에 따라 다르게 동잘 할 수 있음.



keydown() - 키보드가 눌러질 때 발생

keypress() - 글자가 입력될 때 발생

keyup() - 키보드가 떼어질 때 발생




<Script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
$(document).ready(function(){
    
    //회원명 입력시 회원정보 가져오기
    $("#memName").keyup(function(){
        $("#value-keyword").val($(this).val());
    });
    $("#memName").keypress(function(e){
        if(e.which == 13){
            $(this).blur();
        };
    });
    $("#memName").autocomplete({
        source: function(request, response){
            $.ajax({
                url     : "getMemMobileInfo.do",
                type    : "post",
                data    : {memName: $("#value-keyword").val()},
                success : function(data){
                    response($.map(data.DataList, function(item){
                        return{
                            label: item.STR,                            
                            value: item.STR,
                            memCode: item.MEM_CODE,
                            memTypeInput: item.MEM_TYPE_INPUT,
                            memType: item.MEM_TYPE,
                            pushYn: item.PUSH_YN,
                            deviceInput: item.DEVICE_INPUT,
                            device: item.DEVICE,
                            deviceId: item.DEVICE_ID
                        };
                    }))    
                },
                error    : function(request, status, error){
                    alert("회원 이름으로 정보를 불러오는 중 오류가 발생하였습니다.")
                }
            });
        },
        position: {my: "right top", at: "right bottom"},
        minLENGTH: 2,
        focus: function(event, ui){
            return false;
        },
        select: function(event, ui){
            if (ui.item.pushYn == 'N') {
                alert("푸시알림을 거부한 회원은 선택할 수 없습니다.");
                return false;
            }
            //TBL_MEM_MOBILE_INFO. DEVICE 디바이스구분(A:안드로이드, I:아이폰)
            //TBL_PUSH_NOTICE. OS_TYPE OS(1:안드로이드, 2:아이폰, 3:전체)
            if (ui.item.device == 'A') {
                $("#osType").val("1");
                
            } else if (ui.item.device == 'I' ) {
                $("#osType").val("2");
            };             
            //TBL_MEM_MST. MEM_TYPE 회원종류(0:일반회원, 1:부동산회원)
            //TBL_PUSH_NOTICE. MEM_TYPE 회원종류(1:비중개회원, 2:중개회원, 4:분양회원, 7:전체)
            //5:비중개회원(개별), 6:중개회원(개별)
            if (ui.item.memType == '0') {
                $("#memType").val('5');
            } else if (ui.item.memType == '1') {
                $("#memType").val('6');
            };
            $("#memCode").val(ui.item.memCode);
            $("#device").val(ui.item.device);
            $("#osTypeInput").val(ui.item.deviceInput);
            $("#memTypeInput").val(ui.item.memTypeInput);
            $("#memName").blur();
        },
        open: function(e, ui){
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        closefunction(){
            $(this).removeClass("ui-corner-top ui-autocomplete-loading").addClass("ui-corner-all");
        }
    });
})
cs


인터넷 익스플로러에서만 개체가 'includes' 속성이나 메서드를 지원하지 않습니다 에러 발생

크롬에선 잘 되던게... 익스플로러에서만 작동하지 않아 콘솔을 보니.

 

개체가 'includes' 속성이나 메서드를 지원하지 않습니다. 라는 에러가...?

 

 

 

흠...

변수가 object 여서 문젠가 싶어, 문자열로도 테스트를 해봤는데. 어떻게 지지고 볶아도 해결이 되지 않아 검색을 좀 더 해보니...

 

 

요구 사항

Microsoft Edge(Edge 브라우저)에서 지원됩니다. 스토어 앱(Windows 10의 Microsoft Edge)에서도 지원됩니다. 버전 정보를 참조하십시오.

Quirks, Internet Explorer 6 표준, Internet Explorer 7 표준, Internet Explorer 8 표준, Internet Explorer 9 표준, Internet Explorer 10 표준, Internet Explorer 11 표준과 같은 문서 모드에서는 지원되지 않습니다. Windows 8.1에서는 지원되지 않습니다.

 

이건 뭐... 인터넷 익스플로러에서는 거의 안된다는 말과 다름없는.......

ㅎ.........

 

 

대체할 방법은 없는가 싶어 구글링.

그리고 스택 오버플로우에는 이미 나같은 사람들을 위한 답변들이ㅋ

 

참고해서,

.includes() 대신에 .indexOf 로 바꾸니 크롬, 익스플로러 구분없이 잘 된다.

 

 

에러가 발생하는 자바스크립트 소스

1
2
3
4
if (opt.value.includes(search)) {
    sel.selectedIndex = j;
    break;
}
cs

 

 

보완한 자바스크립트 소스

1
2
3
4
if (opt.value.indexOf(search) != -1) {
    sel.selectedIndex = j;
    break;
}
cs

 

 

 

참고

https://msdn.microsoft.com/ko-kr/library/dn858228(v=vs.94).aspx

자바스크립트 체크박스의 .attr(), .prop() 차이는 뭘까?

참고 : http://javascriptandjquerydev.blogspot.kr/2012/07/attr-prop.html

 

체크박스 제어할 때 늘 attr, prop 차이가 궁금했는데 위 사이트에서 설명이 잘 되어 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
//하나더 예를 들어보겠습니다. 체크박스의 checked의 대하여 입니다.
<checkbox id="private" type="checkbox" checked /> 
//체크박스의 checked의 값을 확인합니다.
 
var $checkbox = $('#private'); 
alert($checkbox.attr('checked'));  // checked속성의 값을 표시 → "checked"
alert($checkbox.prop('checked'));  // checked프로파티값을 표시 → true
 
//또 화면의 체크박스를 클릭하여 체크를 해제해보겠습니다.
//•.attr() → "checked"
//•.prop() → false
//.attr()의 경우는 변하지않습니다. 체크가 되어있는지 판단을 할경우 .prop()을 사용할 필요가 있습니다.
cs

 

체크박스를 전체 선택하고 해제하는 스크립트를 쓰려면 .prop()로 true/false 를 제어하자.

 

 

Ajax

Ajax
  • Asynchronous Javascript+XML 을 말한다.
  • JavaScript의 비동기통신(XMLHttpRequest)을 사용해
  • 웹 브라우저의 페이지를 전환하지 않은 채
  • 일부를 수정함으로써
  • 페이지의 사용 편의성을 높여주는 기술이다.
  • 예) 구글 맵에서 지도를 움직이거나 지도에서 가게 정보를 표시하는 것

 

+ Recent posts