donaricano-btn

제이쿼리를 이용하여 요소의 속성 읽기/설정 -  attr(), prop()

- jQuery 1.5 이하에서는 attr() 메소드로 통합하여 취급했지만 1.6  이상에서는 분리하였다


1. attr()

1) 단일 설정

- attr() 함수를 이용하여 특정 요소의 속성에 접근 할 수 있다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
 
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    </style>
 
</head>
 
<div id="container">
    <ul>
        <li id="naver"><a href="www.naver.com" rel="externel">naver</a></li>
    </ul>
</div>
<script>
$(function(){
    $('a[rel="externel"]').attr('title','Move to naver');
});
</script>

2)  복수 설정

- 해쉬 설정으로 복수도 가능하다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
 
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    </style>
 
</head>
 
<div id="container">
   <img src="nba.png" id="#pic">
</div>
<script>
    $(function(){
        $('#pic').attr({
            alt:'image',
            title:'This is a nba'
        })
    });
</script>
 


2. prop()

 - checked, selected, disabled, multiple 프로퍼티 처럼 HTML  프로퍼티와 Javascript 프로퍼티와의 사이에 값이 다른 것에 대해 이용

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
<!DOCTYPE html>
 
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
    </style>
 
</head>
 
<label for="name">Name</label><br/>
<input type="text" id="name" name="name" value="Hee" disabled/>
<br/>
<label for="blood">Blood</label><br/>
<select id="blood" name="blood" multiple>
    <option id="typeA" value="A" selected>A Type</option>
    <option id="typeB" value="B">B Type</option>
</select>
<br/>
<label for="marriage">marriage</label><br/>
<input type="checkbox" id="marriage" name="marriage" value="1" checked/>
 
<script>
    $(function(){
        console.log($('#name').prop('disabled'));
        console.log($('#name').attr('disabled'));
        console.log($('#blood').prop('multiple'));
        console.log($('#blood').attr('multiple'));
        console.log($('#typeA').prop('selected'));
        console.log($('#typeA').attr('selected'));
        console.log($('#marriage').prop('checked'));
        console.log($('#marriage').attr('checked'));
    });
</script>
 

- boolean 형식은 prop() 이 낫다



블로그 이미지

리딩리드

,