기본 콘텐츠로 건너뛰기

개발 공부 - jQuery Traversing(트래버싱)

용어 뜻:
Traversing 기능: 각각의 요소간의 접근방법
예를 들어 어떤 요소의 자식요소, 부모요소를 찾아갈 때 사용하는 방법
요소에 id 속성을 부여해서 접근하는 방법이 있지만 traversing을 사용하면 id를 부여하지 못하는 상황에서도 접근이 가능하다.

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
$('div#zero')
parent
 
부모 태그를 한 번 선택해볼까요? parent 메소드를 사용하면 됩니다.
 
$('div#zero').parent(); // [div.main]
document.getElementById('zero').parentElement;
parents
 
부모부터 시작해서 조상 태그를 모두 선택합니다.
 
$('div#zero').parents(); // [div.main, div#container, body, html]
parentsUntil
 
부모부터 시작해서 선택한 조상 태그 이전까지를 모두 선택합니다.
 
$('div#zero').parentsUntil('body'); // [div.main, div#container]
closest
 
조상 태그를 선택할 수 있습니다. #container을 선택하고 싶다면
 
$('div#zero').closest('#container'); // [div#container]
children
 
자식 태그를 모두 선택할 수 있습니다.
 
$('div#zero').children(); // [p, span, input]
document.getElementById('zero').children;
first
 
선택한 태그 중 첫 번째 태그를 선택합니다.
 
$('div#zero').children().first(); // [p]
document.getElementById('zero').firstChild;
last
 
선택한 태그 중 마지막 태그를 선택합니다.
 
$('div#zero').children().last(); // [input]
document.getElementById('zero').lastChild;
eq
 
선택한 태그 중 n번째 태그를 선택합니다. 순서가 0123, ...이기 때문에 첫 번째 것은 0, 두 번째 것은 1 순으로 갑니다.
 
$('div#zero').children().eq(1); // [span]
document.getElementById('zero').children[1];
find
 
후손 태그를 선택할 수 있습니다.
 
$('div#zero').find('em'); // [em]
document.getElementById('zero').getElementsByTagName('em')
next
 
형제자매 태그 중 다음 태그를 선택할 수 있습니다.
 
$('div#zero').next(); // [div#nero]
document.getElementById('zero').nextElementSibling;
nextAll
 
형제자매 태그 중 다음 모든 태그를 선택합니다.
 
$('div#zero').nextAll(); // [div#nero, div#hero]
nextUntil
 
다음 태그부터 선택한 태그 이전까지를 모두 선택합니다.
 
$('div#zero').nextUntil('div#hero'); // [div#nero]
prev
 
형제자매 태그 중 이전 태그를 선택할 수 있습니다.
 
$('div#zero').prev(); // [nav]
document.getElementById('zero').prevElementSibling;
prevAll
 
형제자매 태그 중 이전 모든 태그를 선택합니다.
 
$('div#nero').prevAll(); // [nav, div#zero]
prevUntil
 
선택한 태그 이후부터 이전 태그까지를 모두 선택합니다.
 
$('div#nero').prevUntil('nav'); // [div#zero]
siblings
 
prevAll과 nextAll을 합쳐놓은 메소드입니다. 모든 형제자매 태그를 선택합니다.
 
$('div#zero').siblings(); // [nav, div#nero, div#hero]
filter
 
선택한 태그들 중에서 원하는 태그를 걸러냅니다.
 
$('div').filter('#zero'); // [div#zero]
이렇게 자유자재로 이동하는 방법을 배웠습니다. 참고로 위의 메소드들은 연달아 사용할 수 있습니다. 메소드 체이닝 기법이라고 불리죠. $('div#zero').prev().parent().next().children().eq(0) 이렇게요.
cs

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
<!DOCTYPE html>  
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        //div요소중 첫번째 요소에 css적용하기
        $("div").first().css("border","3px solid blue");
 
        //div요소중 마지막 요소에 css적용하기
        $("div").last().css("border","3px solid green");
        //id속성이 ari인 요소의 다음요소에 css적용하기
        $("#ari").next().css("color","orange");
//id속성이 ari인 요소의 부모요소에 css적용하기
        $("#ari").parent().css("backgroundColor","yellow");
        //pp의 자식요소중 .aa에 적용
        $("#pp").find(".aa").css("fontSize","30px");
        //pp의 모든 자식요소 얻어오기
        var child=$("#pp").children();
        //alert("자식의 갯수:" + child.length);
        //pp의 모든 자식요소의 html값 출력하기
        child.each(function(index){
            alert("[" +index + "]"+ $(this).html());
        });
    });
</script>
</head>
<body>
<div id="pp" class="aa">
    <div id="ari">아리랑 아리랑 아라리요</div>
    <div class="aa">아리랑 고개로 넘어간다.</div>
    <div>나를 버리고 가시는 님은</div>
</div>
<div class="aa">
    십리도 못가서 발병난다.
</div>
</body>
</html>
 
cs

이런 경우에는 div의 첫번째/마지막 요소를 얻어와서 속성값을 달리 할 수 있다.

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    label{display:inline-block;width:150px;}
    form span{color:red;font-size: 12px;}
</style>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    //클래스속성이 requried요소에 포커스가 들어오면 메시지 span에 출력
        $(".required").focusin(function(){
            $(this).next().html("필수입력사항입니다");
        });
// 클래스속성이 requried요소에 포커스가 나가면 메시지 span에서 지우기
        $(".required").focusout(function(){
            $(this).next().html("");
        });
        
    });
</script>
</head>
<body>
<form action="register.jsp">
    <label>아이디(*)</label><input type="text" class="required" id="id"><span></span><br>
    <label>비밀번호(*)</label><input type="password" class="required" id="pwd"><span></span><br>
    <label>비밀번호확인(*)</label><input type="password" class="required" id="pwd1"><span></span><br>
    <label>이메일</label><input type="text"><br>
    <input type="submit" value="등록">
</form>
</body>
</html>
cs

이런 경우에는 필수 입력란에 포커스가 들어오면 span 태그 부분에 문장을 출력한다.
포커스가 들어온 요소의 다음 요소에 메시지를 출력하면 된다.

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
78
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
    *{margin:0;padding:0}
    #list{width:850px;height: 170px;background-color: #a6a6a6;
                    margin:30px auto;border-radius:20px}
    #list ul{padding:5px;list-style: none;}
    #list ul li{float:left;position: relative;}
    #list ul li img{width:200px;height: 150px;margin:5px;border-radius:20px}
    #content{clear: both;width:600px;height: 400px;padding:10px;
            margin:auto;position: relative;}
span{font-size: 20px;font-weight: bold;font-family: Arial;
    text-shadow: 3px 3px 3px #777;color:yellow;
    position: absolute;left:20px;top:20px;display: none}
#wrap{background: #dddddd;width:900px;
height: 700px;padding:30px;margin: auto}
#img1{
    width:600px;
    height:400px;
    background-image: url('images/5.jpg');
    background-size:100% 100%;
    border:5px solid white;
    border-radius:30px;
    transition:all 1s;
}
</style>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#list ul li").hover(function(){
//마우스가 올라온 li요소의 자식요소중 img에 css효과를 //적용합니다.
            $(this).find("img").css("opacity","0.3");
            $("#img1").css("border-radius","50% 50%");
//마우스가 올라온 li요소의 자식요소중 span에 slideDown을 주어서 화면에서 //안보이게 합니다.
 
            $(this).find("span").slideDown(500);
//마우스가 올라온 li요소의 자식요소 img에 src속성값을 아래 큰 이미지의
//background-image 이미지로 설정합니다.
 
            var src=$(this).find("img").attr("src");
            $("#img1").css("background-image","url(" + src + ")");
    //마우스가 올라온 li요소의 자식요소 span의 텍스트를 아래큰이미지 //위에 보이도록 apppendTo()함수로 추가합니다.
            var txt=$(this).find("span").text();
            $("<span>" + txt + "</span>").appendTo("#img1").css({
                "left":"130px",
                top:"150px",
                fontSize:"50px"
            }).slideDown(500);
            
        },function(){
//마우스가 벗어나면 자식요소의 img요소를 원래 밝기로 보여지게 합니다.
            $(this).find("img").css("opacity","1");
            $("#img1").css("border-radius","30px");
            $(this).find("span").slideUp(500);
            $("#img1 span").remove();
        });
    });
</script>
</head>
<body>
<div id="wrap">
    <div id="list">
        <ul>
            <li><img src='images/1.jpg'><span>Beautiful Picture1</span></li>
            <li><img src='images/2.jpg'><span>Beautiful Picture2</span></li>
            <li><img src='images/3.jpg'><span>Beautiful Picture3</span></li>
            <li><img src='images/4.jpg'><span>Beautiful Picture4</span></li>
        </ul>
    </div>
    <div id="content">
        <div id="img1"></div>
    </div>
</div>
</body>
</html>
cs

자식요소의 속성값을 변화시킬 수도 있다.

APIcategory:traversingalso in
01.add()이미 선택된 요소들과 주어진 선택자에 매치되는 요소들의 합집합Traversing > Miscellaneous Traversing
02.addBack()Add the previous set of elements on the stack to the current set, optionally filtered by a selector.Traversing > Miscellaneous Traversing
03.andSelf()Add the previous set of elements on the stack to the current set.Deprecated > Deprecated 1.8 | Traversing > Miscellaneous Traversing
04.children()Get the children of each element in the set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
05.closest()For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.Traversing > Tree Traversal
06.contents()Get the children of each element in the set of matched elements, including text and comment nodes.Traversing > Miscellaneous Traversing
07.each()Iterate over a jQuery object, executing a function for each matched element.Miscellaneous > Collection Manipulation
08.end()End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.Traversing > Miscellaneous Traversing
09.eq()Reduce the set of matched elements to the one at the specified index.Traversing > Filtering
10.filter()Reduce the set of matched elements to those that match the selector or pass the function’s test.Traversing > Filtering
11.find()Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.Traversing > Tree Traversal
12.first()Reduce the set of matched elements to the first in the set.Traversing > Filtering
13.has()Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.Traversing > Filtering
14.is()Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.Traversing > Filtering
15.last()Reduce the set of matched elements to the final one in the set.Traversing > Filtering
16.map()Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.Traversing > Filtering
17.next()Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.Traversing > Tree Traversal
18.nextAll()Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
19.nextUntil()Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.Traversing > Tree Traversal
20.not()Remove elements from the set of matched elements.Traversing > Filtering | Traversing > Miscellaneous Traversing
21.offsetParent()Get the closest ancestor element that is positioned.Offset | Traversing > Tree Traversal
22.parent()Get the parent of each element in the current set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
23.parents()Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
24.parentsUntil()Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.Traversing > Tree Traversal
25.prev()Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
26.prevAll()Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
27.prevUntil()Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.Traversing > Tree Traversal
28.siblings()Get the siblings of each element in the set of matched elements, optionally filtered by a selector.Traversing > Tree Traversal
29.slice()Reduce the set of matched elements to a subset specified by a range of indices.Traversing > Filtering


출처:
IT로 하나되는 세상, 2016-10-31, http://m.blog.naver.com/jhtastyle/220717197021
dd2i_pudding, 2016-10-31, http://dondon2i.tistory.com/297

댓글

  1. 전 회사에서 이거 때문에 많이 고생함.
    HTML 내에 HTML 내에 HTML 내에 HTML 이런 식이라서 엄청나게 고생함.

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

Ebook - 전자책 drm 상관 없이 pdf로 만들기

yes24와 교보문고에서 ebook을 구매 해야 했는데 너무 불편하고, 필기가 매우 화날 정도로 안 좋아서 원시적으로 사용하기로 했다. 1. 목적 : ebook에서 필기 및 사용이 불편하여 pdf로 변환  2. 용도 : 개인 사용 목적이며 화질이 다소 저하되어도 필기만 용이하면 상관 없음 3. 방법 1) 휴대폰 및 카메라로 동영상을 촬영했다. DRM 때문에 프로그램으로는 촬영이 안 되는 것을 확인했다. 2) 마우스 클릭 해주는 매크로를 사용했다. (1) key_macro.exe > https://blog.daum.net/pg365/250 듀얼 모니터에서 위치 이탈 현상이 있긴 해도 괜찮았다. (2) AutoClick.exe > http://bestsoftwarecenter.blogspot.com/2011/02/autoclick-22.html 이 걸로 잘 사용했다. 3초마다 한 번 클릭하도록 사용했다. 3) 동영상을 이미지로 변경해주는 프로그램을 사용했다. Free Video to JPG Converter > https://free-video-to-jpg-converter.kr.uptodown.com/windows 일 하면서 듀얼 모니터에 켜 놨는데 속도가 괜찮았다. * Every frame 으로 사용해야 한다. 4) 중복 사진 제거해주는 프로그램을 사용했다. VlsiPics  > http://www.visipics.info/index.php?title=Main_Page 생각보다 느리니 퇴근시에 걸어놓고 가면 된다. 한번 play가 끝나면 Auto-select 하고 Delete 하면 된다. 5) 이미지를 일괄 Crop 작업 해주는 프로그램을 사용했다. JPEGCrops > https://jpegcrops.softonic.kr/ * https://joker1209.tistory.com/11 도 참고했다. View -> Large 로 크게 본 뒤, Edit -> Syncronize Crops 로 일괄 동일하게 적용하는 방식을 사

개발 공부 - json JSONObject 사용 시 백슬래시(\), 원화 표시(\) 제거 및 치환

import org.json.simple.JSONObject; String dataString = new String(authData.toJSONString()); dataString = dataString.replaceAll("\\\\", ""); String 으로 안 바뀌는 가 싶어서 String 으로 변환 해 주고 작업 하였다. 사실 toJSONString 해도 정상 동작 해야 하는데 이유를 잘 모르겠음. 그리고 나서 다시 이클립스 구동 하니 toString 도 먹은 걸로 봐서 이상하다고 생각! String dataString = authData.toString(); dataString = dataString.replaceAll("\\\\", ""); 어쨌든 백 슬래시 제거를 해줘야 하는데 \\ 도 아니고 \\\\를 해야 변환이 가능했다는 결말이었습니다. 참고 : https://stackoverflow.com/questions/15450519/why-does-string-replace-not-work/15450539 test =test.replace("KP", "");  replace 후에 담아 주지 않으면 적용이 안 됩니다!

개발 공부 - OracleXETNSListener 서비스가 로컬 컴퓨터에서 시작했다가 중지되었습니다.

여러 가지 요인이 있지만 PC 이름 변경시 OracleXETNSListener 서비스 시작이 불가능합니다. 고치는 법은 C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN 와 같은 설치 경로에서 listener.ora와 tnsnames.ora 의 pc명을 바꾼 PC명으로 바꿔주면 됩니다. 그래도 안 된다면 cmd 창에서 services.msc 를 입력 후 OracleXETNSListener 서비스를 시작 시키면 됩니다. 오류명: OracleXETNSListener 서비스가 로컬 컴퓨터에서 시작했다가 중지되었습니다. 일부 서비스는 다른 서비스 또는 프로그램에서 사용되지 않으면 자동으로 중지됩니다. 참고한 사이트들 1. http://blog.naver.com/visioner7/120165951652 2. http://database.sarang.net/?inc=read&aid=6819&criteria=oracle&subcrit=&id=&limit=20&keyword=ora-12560&page=5 이런 걸 보면 오라클은 앙칼진 시골 아가씨야