메서드 (3)

💻 Programming/웹프로그래밍

[jQuery] 4. DOM Attributes ( DOM 속성 )

 

Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.

Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:

  • className

  • tagName

  • id

  • href

  • title

  • rel

  • src

Consider the following HTML markup for an image element:

<img id="myImage" src="image.gif" alt="An image" 
class="someClass" title="This is an image"/>

In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value.

jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.


속성값 읽어오기

속성값은 attr(name) 메소드를 이용하여 읽어올 수 있습니다.

예제:

아래 예제는 em요소의 title속성에 지정된 값을 읽어와서 div요소에 출력하는 예제네요.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      var title = $("em").attr("title");
      $("#divid").text(title);
   });

   </script>
</head>
<body>
   <div>
      <em title="Bold and Brave">This is first paragraph.</em>
      <p id="myid">This is second paragraph.</p>
      <div id="divid"></div>
   </div>
</body>
</html>

 

 

속성값 수정하기

 attr(name, value) 메소드를 이용하여 특정 속성명에 대한 속성값을 설정해줄 수 있습니다.

예제:

아래 예제는 src 속성에 특정 파일경로를 설정해주는 예제입니다.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("#myimg").attr("src", "/images/jquery.jpg");
   });

   </script>
</head>
<body>
   <div>
      <img id="myimg" src="/wongpath.jpg" alt="Sample image" />
   </div>
</body>
</html>

 

 

스타일 적용하기

 addClass( classes ) 메소드를 이용하여 정의한 스타일을 적용시킬 수 있습니다.  여러개의 클래스를 스페이스를 구분자로 지정해줄 수 있습니다.

예제:

아래 예제는 문서내의 모든 em요소에 selected스타일을 적용시키고, id가 myid인 요소에는 highlight스타일을 적용시키는 예제입니다.
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>

 

 

유용한 속성 관련 메소드 목록

 

MethodsDescription
attr( properties )Set a key/value object as properties to all matched elements.
attr( key, fn )Set a single property to a computed value, on all matched elements.
removeAttr( name )Remove an attribute from each of the matched elements.
hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class )Removes all or the specified class(es) from the set of matched elements.
toggleClass( class )Adds the specified class if it is not present, removes the specified class if it is present.
html( )Get the html contents (innerHTML) of the first matched element.
html( val )Set the html contents of every matched element.
text( )Get the combined text contents of all matched elements.
text( val )Set the text contents of all matched elements.
val( )Get the input value of the first matched element.
val( val )Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.

Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:

  • $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.

  • $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".

  • $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.

  • $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank

  • $("a").removeAttr("target") : This would remove target attribute of all the links.

  • $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.

  • $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected.

  • $("p").text(): Returns string that contains the combined text contents of all matched <p> elements.

  • $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> elements

  • $("p").html() : This returns the HTML content of the all matching paragraphs.

  • $("div").html("Hello World") : This would set the HTML content of all matching <div> to Hello World.

  • $("input:checkbox:checked").val() : Get the first value from a checked checkbox

  • $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons

  • $("button").val("Hello") : Sets the value attribute of every matched element <button>.

  • $("input").val("on") : This would check all the radio or check box button whose value is "on".

  • $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange, Mango and Banana.

  • $("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-attributes.htm 

 

 

 

 

 

 

이번에는 자바스크립트의 함수에 대해서 알아보도록 하겠습니다.  

함수가 뭐냐? 모르시는 분이 계시려나요? 자바나 C의 메소드, 함수랑 똑같은 겁니다.

함수는 function 키워드를 이용해서 정의하는데 function의 영어 의미를 찾아보면 다음과 같습니다.

1.명사 (사람사물의) 기능
2.명사 행사, 의식
3.동사 (제대로) 기능하다[작용하다] (=operate)

따라서 함수는 특정 기능을 하는 놈이구나~ 라고  이해하시면 됩니다.

내가 원하는 어떤 기능을 하도록 만드는 것이죠.

 

자, 그럼 문법을 한번 살펴보겠습니다.

<script type="text/javascript">

function 함수명( 파라미터 리스트 )
{
  // statements
}

</script>

 

 

위 문법은 함수를 선언하는 것입니다. 아래처럼 사용할 수 있죠. 

<script type="text/javascript">

function sayHello()
{
   alert("Hello there");
}

</script>

 

 

 

자, 그럼 이렇게 선언해놓은 함수를 어떻게 호출을 할까요?

 

네~ 그렇죠~ 제가 늘 말하는 "아래처럼" 호출하면 되는겁니다~

 

<script type="text/javascript">

sayHello();

</script>

 

 

파라미터

이번에는 파라미터 사용법에 대해서 알아보도록 하겠습니다.

 

자바스크립트의 특징 중 하나가  undefined type이었다는 것을 기억하시나요? 변수를 지정할때 타입을 지정하지를 않죠?  

함수내에 파라미터를 넣을때도 타입을 지정하지 않습니다. 아래처럼 말이죠. 

<script type="text/javascript">

function sayHello(name, age)
{
   alert( name + " is " + age + " years old.");
}

</script>

 

위 소스를 보시면 sayHello()가 파라미터 두개를 받고있네요. name과 age.  

이 함수를 호출할 때에는 파라미터를 두개 넣어주면 되는 겁니다. 

<script type="text/javascript">

sayHello('Zara', 7 );

</script>

 

sayHello 함수에 'Zara' 랑 7을 파라미터로 넘겼네요. Zara의 홑따옴표는 스트링을 의미합니다. Zara라는 스트링을 파라미터로 넘긴다는 말이죠. 

return

자바스크립트의 함수도 결과값을 반환할 수 있습니다. 

 

예제를 한번 볼까요? 

 

<script type="text/javascript">

function concatenate(first, last)
{
   var full;

   full = first + last;
   return  full;
}

</script>

위 소스는 두개의 파라미터를 받아서 두개를 합친 결과를 반환합니다.

 

이제 함수를 호출해서 함수에서 얻은 결과값을 경고창에 띄워보겠습니다. 

<script type="text/javascript">

   var result;
   result = concatenate('Zara', 'Ali');
   alert(result );

</script>

 

 

함수에 대해서 좀 더 자세한 내용을 알고싶으면 아래 링크를 참조하세요 ^____^

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_functions.htm 

 

 

 

안녕하세요, 오늘도 어김없이 꿀팁을 들고온 케이치입니다 ^-^ ㅎㅎ

 

오늘은 안드로이드 스튜디오에서 기본적으로 보여주지 않고있는 메소드 description에 대한 것입니다.

 

이클립스는 기본적으로 메소드 위에 마우스 커서를 올려놓으면 메소드에대한 설명이 나오는데요

 

안드로이드 스튜디오는 기본적으로 그렇지가 않더군요. ㅜㅜ

 

구글링하면 나오기는 하는데 2014년도 버전과 최근 없데이트된 버전이 또 조금 다르더군요.

 

자, 우선 메소드 설명을 보는 방법 몇 가지를 소개해드리겠습니다.

 

 

 

1. description을 보고자하는 메소드명에 커서가 위치하도록 마우스로 클릭하고 Ctrl + Q ( Windows )를 누른다.

 

아래는 Texture에다가 커서가 깜박이도록 한 뒤 Ctrl + Q 를 눌렀을 때 나오는 팝업입니다.

 

 

 

 

2. 이클립스처럼 마우스 커서를 올려만 놔도 자동으로 메소드 디스크립션을 띄우려면

File >> Setting >> Editor >> General >> Other >> Show quick doc on mouse move 에 체크를 해줍니다.

 

 

 

3. 세번 째는 수동으로 파일을 수정하는 방법입니다.

 

IntelliJ의 bin디렉토리에 보시면 idea.properties라는 파일이 있는데 여기에 auto.show.quick.doc=true 를 추가해주시면 됩니다. 

 

이 세번째 방법은 직접 검증 해보진 않았고 구글링에서 나온 얘기를 그냥 덧붙인것입니다. 첫번째, 두번째 방법처럼 쉬운 방법이 있는데 궂이 이 방법을 쓸 이유는 없겠죠? ㅋ

 

 

자~ 그럼 오늘도 즐프~~