728x90

자바스크립트에서 속성 읽기, 설정, 제거하는 방법이다.

<a id="target" href="http://abc.com">tutorials</a>

<script>

var t = document.getElementById('target');

t.getAttribute('href'); // href 속성의 값을 가져온다.

t.setAttribute('title', 'abcdef'); // title 속성의 값을 설정한다.

t.removeAttribute('title'); // title 속성을 제거한다.

</script>


jQuery는 HTML 요소에 대해 객체를 통하여 속성 값을 제어할 수 있는 attr()함수를 제공한다.


var 변수 = $("요소").attr("속성이름"); // 속성 값 읽기

var 변수 = $("요소").attr("속성이름","값"); // 속성 값 변경/추가


예제1

<div id="ajaxPath" data-path="<?php echo $g['path_page'].'process/'; ?>" ></div>


var loginpath =$("#ajaxPath").attr('data-path');
$.ajax({
    url: loginpath+'updateUser.php',
    type: 'POST',
    data: {
        idx:$("#memberidx").val(),
        userNM:$("#memberName").val(),
        mobileNO:$("#memberMobile").val()
    },
    dataType: "json",
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function (response) {
        if(response.result == 1){
            alert('수정 완료');
            location.replace('index.php'); // 화면 갱신
        } else if(response.result == 0){
            alert('수정 실패');
        }
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert("ajax error : " + textStatus + "\n" + errorThrown);
    }
});


예제2

<span class="button" id="errorChk" data-uid="<?=$R['uid']?>">오류</span>


$("#errorChk").click(function(){
    uid=$(this).attr("data-uid");
    ErrorDisplay(uid);
});

function ErrorDisplay(_uid){
    $.get("ErrorChk.php", {uid:_uid}, function(data){
        $("#dialog").dialog("open").html(data);
    });
}

function ErrorChk(_uid,_mod){
    $.get("ErrorChk.php", {uid:_uid, mod:_mod}, function(data){
        $("#dialog").dialog("open").html(data);
    });
}


prop() 함수 : 선택한 요소에 속성을 반환/생성/변환한다.

주의할 점은 HTML 입장에서의 속성(attribute)이 아닌 Javascript 입장에서의 속성(property)이다.

jQuery 1.6 부터 prop()함수가 추가되어 attr()함수의 역할을 나누게 되었다.


다음 예제를 통해 결과가 어떻게 다른지 확인해보자.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var prop_id = $(":text").prop("id");
    var attr_id = $(":text").attr("id");

    alert("prop id값  : " + prop_id + " , attr id값 : " +  attr_id);


    var prop_class = $(":text").prop("class");
    var attr_class = $(":text").attr("class");

    alert("prop class값 : " + prop_class + " , attr class값 : " +  attr_class);


    var prop_readonly = $(":text").prop("readonly");
    var attr_readonly = $(":text").attr("readonly");

    alert("prop readonly값 : " + prop_readonly + " , attr readonly값 : " +  attr_readonly);


    var prop_disabled = $(":text").prop("disabled");
    var attr_disabled = $(":text").attr("disabled");
    alert("prop disabled값 : " + prop_disabled + " , attr disabled값 : " +  attr_disabled);
})
</script>
</head>
<body>
<input type="text" id="text_field" class="text_class" readonly="readonly" disabled="disabled" />
</body>
</html>


prop id값  : text_field , attr id값 : text_field

prop class값 : text_class , attr class값 : text_class


prop readonly값 : true , attr readonly값 : readonly

prop disabled값 : true , attr disabled값 : disabled


<input id="chk" type="checkbox" checked="checked" />
먼저 attr 함수로 checked 속성 값을 가져오면 그 결과 값은 checked(HTML이 가지고 있는 속성의 text 값)로 나온다.
하지만, prop 함수로 checked 속성 값을 가져오면 그 결과 값은 true(속성이 실제 의미하는 값)가 된다.

먼저 attr 함수로 checked 속성 값을 가져오면 그 결과 값은 checked(HTML이 가지고 있는 속성의 text 값)로 나온다.

하지만, prop 함수로 checked 속성 값을 가져오면 그 결과 값은 true(속성이 실제 의미하는 값)가 된다.



출처: http://ggmouse.tistory.com/92 [초보개발자꽁쥐]

true / false체크 같은 것을 사용할 때 아주 유용하다.
prop가 나온후로는
$("요소").prop("checked",true);
$("요소").prop("checked",false);
로 변경을 해주어야 체크박스 핸들링이 가능하다.

블로그 이미지

Link2Me

,