[Attr]

 

요기능은 잘 쓴다고 하니 잘 익혀두자 !!

 

[속성 읽기]

$("선택자").attr("속성명") 

요렇게 사용

$("선택자").get(인덱스).속성명 

요렇게도 가능한 것

해당 태그에 속성명 미 기술시에는 읽어 오지 못함

그래서 읽을 땐 prop()사용 !

 

[속성 설정]

$("선택자").attr("속성명","속성값")
동시에 여러 속성 설정시에는 메소드 체인을 이용하거나 JSON데이타 형식 사용
 attr({속성1:'속성1값',속성2:속성2값.....})

 

[속성 제거]

$("선택자").removeAttr("속성명"); 

 

****속성 추가 시는 attr()이나 prop()사용
 속성 읽기 시는 prop()사용 ,만약 HTML태그상에 속성이 기술이 안되어 있다면 
      attr()은 undefined
      prop()은 빈 문자열 이기 때문...
속성 삭제 시에는 removeAttr()사용.

(removeProp()은   HTML태그의 속성은 제거가 안된다.)

 

 

폼(추가/읽기/제거)

<fieldset>
    <legend >attr()함수 및 removeAttr(),prop()함수</legend>
    <button id="add">속성추가</button>
    <button id="read">속성읽기</button>
    <button id="remove">속성제거</button>
</fieldset>

 

1.속성 추가

$('#add').click(function(){
    attr()함수사용 (메소드 체인)
 	$('#div').attr('title','여기를 클릭 하세요')
             .attr('class','bg')
             .attr('style','width:100px; height:100px;text-align:center;line-height:100px')
             .on('click',function(){
                $(this).html('JQUERY');
             }); 

    JSON데이터 형식 사용
    $('#div').attr({title:'여기를 클릭하세요','class':'bg','style':'width:100px; height:100px;text-align:center;line-height:100px'})
             .on('click',function(){
                $(this).html('JQUERY');
             });           
});

 

2.속성 읽기

**태그의 class속성은 className으로 접근한다

 $('#read').click(function(){
    console.log('체크박스 checked속성(attr함수):',$(':checkbox').attr('checked'));  // undefined 얘는 값을 그대로 읽어 옴
    console.log('체크박스 checked속성(prop함수):',$(':checkbox').prop('checked'));  //false 상태를 보고 true/false 반환

    console.log('링크태그의 href속성(attr함수):',$('#atag').attr('href'));   // #
    console.log('링크태그의 href속성(prop함수):',$('#atag').prop('href'));   // http://127.0.0.1:5500/core/Attr.html#

    console.log('div태그의 class속성(attr함수):',$('#div').attr('class'));   // undefined    bg
    console.log('링크태그의 class속성(prop함수):',$('#div').prop('class'));   // <empty string>  bg

	**태그의 class속성은 className으로 접근한다 (왜? class 자바스크립트의 키워드임 !)
    console.log('div의 class속성:', $('#div').get(0).class);  //undefined 없어..
    console.log('div의 class속성:', $('#div').get(0).className); //bg
    })

3.속성 제거

 $('#remove').click(function(){  
    $('div').removeAttr('class').removeAttr('style');  //제거 잘 됨
    $('div').removeProp('class').removeProp('style');   //제거 안됨
})

 

 

연습!

<div id="div" >DIV태그</div>		
<button id="1">1번 이미지</button>
<button id="2">2번 이미지</button>
<button id="3">3번 이미지</button>
<button id="4">4번 이미지</button>
<br />
<img src="#" alt="이미지" /><br />
<a>href속성을 미 지정한 A태그</a><br />
<input type="text"	size="30" />
<input value="확인" type="button" id="button" />

<hr />
<input type='checkbox' />체크박스
<a href="#" id="atag">A태그</a>
<input type="button" id="chkbtn" value="attr및 prop으로 체크 설정하기" />

버튼의 속성 (id값 ) 가져와서 이미지 변경하기

 $('button').click(function(){
    $('img').attr('src','../images/'+this.id+'.jpg');
})

 

value속성이없는type=text의 값읽어오기 : val()이 유리

 $('#button').click(function(){
    console.log('attr():',$(':text').attr('value'));
    console.log('prop():',$(':text').prop('value'));
    console.log('val():',$(':text').val());  //value속성을 함수로 만들어 놓은것
});

attr만 못 읽어 옴

 

동적으로 체크하기(체크 되어 있으면 해제, 해제되어 있으면 체크 )

$('#chkbtn').click(function(){
    if($(':checkbox').prop('checked'))
        $(':checkbox').prop('checked',false);
    else 
    $(':checkbox').prop('checked',true);


    if($(':checkbox').attr('checked'))
        $(':checkbox').attr('checked',false);
    else 
        $(':checkbox').attr('checked',true);
})

 


[TextHtml]

[시작태그와 종료태그 사이의 컨텐츠 읽어 오기]
    text()혹은 html();
    html()함수는 태그 포함 모든 내용을 읽어오고
    text()함수는 태그부분 제외한 텍스트 부분만 읽어옴

 [시작태그와 종료태그 사이의 컨텐츠 출력하기]
    text("설정할 문자열")혹은 html("설정할 문자열");
    html()함수는 출력시 태그가 해석 되서 출력됨.
    text()함수는 태그가 그대로 출력됨.

 

헷깔리네...

<fieldset>
    <legend>string text() 및 string html()함수</legend>
    <button id="read">읽기</button>
    <button id="write">쓰기</button>
    <button id="img">이미지 추가</button>
    <button id="btnText">버튼태그사이의 텍스트 얻기</button>
    <div><h2>제목입니다.</h2></div>
    <div id="display"></div>
</fieldset>

 

$('button').click (function(){
    switch(this.id){
        case 'read':
            var html=$('div:eq(0)').html(); 
            var text=$('div:eq(0)').text(); 
            console.log('html():%s,text():%s',html,text)
            break;
        case 'write': 
           // $('#display').html('<h3>시작태그와 종료태그사이에 넣기</h3>');  //글씨만 나옴
              $('#display').text('<h3>시작태그와 종료태그사이에 넣기</h3>');  //태그가 그대로 나옴
         break;
        case 'img' : 
        $('#display').html("<img src='../images/1.jpg' alt='이미지'/>")
            break;
        default : console.log($(this).html())
    }
 });

이미지는 읽어올 수가 없으니 alt인 이미지가 출력되고 콘솔창에 주소가 출력 됨


[EachIndex]

index():부모 자식 구조 안에서의 인덱스를 의미 !!! 인덱스 당연히  0부터 시작하고

 한 집안 내 에서의 서열?을 의미한다.... 

<fieldset>
    <legend>each(콜백함수)함수 및 index()함수</legend>
    <div>DIV1</div>
    <div>DIV2</div>
    <div>DIV3</div>
    <div>DIV4</div>
</fieldset>
<div>DIV5</div>

구조안에서의 관계를 잘 생각해!!

var clickDiv = $('div').click(function(){
    console.log('클릭한 div의 인덱스:',$(this).index());  
    //DIV1을 클릭했는데 인덱스가1임 ??!!  DIV5를 클릭하면 인덱스가 1!!!!! 
});

DIV1은 부모가 fieldset 이고 두 번째 자식이니까 인덱스가 1

DIV5는 부모가 body이고 얘도 두 번째 자식이라서 인덱스가 1

 

console.log(clickDiv); // 클릭이벤트가 걸린 모든 div   { 0: div, 1: div, 2: div, 3: div, 4: div 총 5개 !}
console.log(clickDiv.html());  //무조건 1번째요소의 컨텐츠만 가져옴  이때! each함수 사용!

clickDiv.each(function(index,element){   //요 element는 자바스크립트DOM객체!
    console.log('index:',index, ',element:',element.innerHTML)
});

 

 

var colors=['#ff0000','#00ff00','#0000ff','#89afbc','gray'];
    $('div').each(function(index,item){
        $(item).attr({style:"background-color:"+colors[index]}); 이렇게해도 되고
        $(this).attr({id:"div"+index,style:"background-color:"+colors[index]}); 요렇게도 되고
    })

    //동적으로 부여된 아이디값으로 선택. 오 신기
    console.log($('#div0').prop('style'));  //CSS2Properties { "background-color" → "rgb(255, 0, 0)" }
    console.log($('#div0').attr('style'));  //background-color:#ff0000

    //hover적용
    $('div').each(function(){
        //원래 배경색
        var bgColor=$(this).css('backgroundColor');

        $(this).hover(function(){
            $(this).css('backgroundColor','yellow');
        },function(){
            $(this).css('backgroundColor',bgColor);
        })
    });

 

+ Recent posts