출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

지시어

 

 

 

 

기본적인 page 지시어는 자동 생성됨.

 

 

 

 

 

예제

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Frame Include</title>
<style>

div.header {
   text-align: center;
}

div.nav {
   text-align: center;
}

div.news, div.shopping {
   width: 45%;
}

div.news {
   float: left;
}

div.shopping {
   float: right;
}

div.footer {
   clear: both;
   text-align: center;
}
</style>
</head>
<body>

   <div class="header">
      <h1>include 지시어 : Header</h1>
      <hr>
   </div>

   <div class="nav">[게임] [쇼핑] [뉴스]</div>

   <div class="contents">
      <div class="news">
         <h3>[최신 뉴스]</h3>
         <hr>
         코로나 바이러스 발생 현황
      </div>

      <div class="shopping">
         <h3>[쇼핑정보] 인기상품</h3>
         <hr>
         좋은 스마트폰
      </div>
   </div>

   <div class="footer">copyright 2020@</div>

</body>
</html>

 

 

지시어를 사용해 위와 같은 페이지 만들기

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Frame Include</title>
<style>
div.header {
	text-align: center;
}

div.nav {
	text-align: center;
}

div.news, div.shopping {
	width: 45%;
}

div.news {
	float: left;
}

div.shopping {
	float: right;
}

div.footer {
	clear: both;
	text-align: center;
}
</style>

</head>
<body>

	<%@ include file="header.jsp"%>
	<%@ include file="nav.jsp"%>

	<div class="contents">
		<%@ include file="news.jsp"%>
		<%@ include file="shopping.jsp"%>

	</div>


  <%@ include file="footer.jsp" %>

</body>
</html>

 

header.jsp / footer.jsp / nav.jsp / new.jsp / shopping.jsp 각각생성

//header.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <div class="header">
      <h1>include 지시어 : Header include 처리</h1>
      <hr>
   </div>
   
   
 //footer.jsp
 
   <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<div class="footer">copyright 2020@</div>



//nav.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<div class="nav">[게임] [쇼핑] [뉴스]</div>


//news.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
      <div class="news">
         <h3>[최신 뉴스]</h3>
         <hr>
         코로나 바이러스 발생 현황
      </div>
      
      
// shopping.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
      <div class="shopping">
         <h3>[쇼핑정보] 인기상품</h3>
         <hr>
         좋은 스마트폰
      </div>

 

액션

 

 

인클루드 / include 액션 / param

 

예제1)

 

위의 index.jsp에 footer 부분을 수정

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Frame Include</title>
<style>
div.header {
	text-align: center;
}

div.nav {
	text-align: center;
}

div.news, div.shopping {
	width: 45%;
}

div.news {
	float: left;
}

div.shopping {
	float: right;
}

div.footer {
	clear: both;
	text-align: center;
}
</style>

</head>
<body>

	<%@ include file="header.jsp"%>
	<%@ include file="nav.jsp"%>

	<div class="contents">
		<%@ include file="news.jsp"%>
		<%@ include file="shopping.jsp"%>

	</div>

	<jsp:include page="footer.jsp">
		<jsp:param name="email" value="test@test.net" />
		<jsp:param name="tel" value="000-000-0000" />
	</jsp:include>



</body>
</html>

footer.jsp 부분도 수정

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<div class="footer">copyright 2020@</div>
<div class="footer">email: <%= request.getParameter("email") %> , 
tel: <%= request.getParameter("tel") %></div>

실행 결과

 

포워드 forward 액션

 

예제2)

 

index.html에 forward page를 사용하면

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Frame Include</title>
<style>
div.header {
	text-align: center;
}

div.nav {
	text-align: center;
}

div.news, div.shopping {
	width: 45%;
}

div.news {
	float: left;
}

div.shopping {
	float: right;
}

div.footer {
	clear: both;
	text-align: center;
}
</style>

</head>
<body>

	<%@ include file="header.jsp"%>
	<%@ include file="nav.jsp"%>

	<div class="contents">
		<%@ include file="news.jsp"%>
		<%@ include file="shopping.jsp"%>

	</div>

	<jsp:forward page="footer.jsp">
		<jsp:param name="email" value="test@test.net" />
		<jsp:param name="tel" value="000-000-0000" />
	</jsp:forward>


</body>
</html>

footer 페이지만 보여지게 된다.

'JAVA > Jsp&Servlet' 카테고리의 다른 글

[JSP] 쿠키  (0) 2020.12.17
[JSP] 에러  (0) 2020.12.17
[JSP] beans 빈즈  (0) 2020.12.17
[JSP] 내장객체와 속성관리 / 생명주기  (0) 2020.12.16
[JSP] 기본 객체와 영역 / 내장객체 / request / response / .. etc  (0) 2020.12.15
[JSP] JSP / 서블릿 작성  (0) 2020.12.14
[JSP] apache tomcat 톰캣 환경설정  (0) 2020.12.14

 

생성!

 

 

JSP 파일 만들고 작성하기 

 

 

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.Date" %>

<%
	Date now = new Date();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>now Date</title>
</head>
<body>

<h1>현재시간 : <%= now %></h1>

</body>
</html>

 

 

 

서블릿 작성

 

- 서블릿이란 서블릿 클래스를 상속해서 만들어진 객체이다.
- 웹 컨테이너는 서블릿 클래스를 가지고 서블릿 객체를 만든 다음 그 객체를 초기화해서 웹 서비스를 할 수 있는 상태로 만드는데, 이 작업을 거친 서블릿 객체만 서블릿이라고 할 수 있다.

 

 

package test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class firstweb1
 */
@WebServlet("/now1")
public class firstweb1 extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		System.out.println("GET 방식의 요청");
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// doGet(request, response);
	}

}

 

 


 

 

그냥 일반 클래스 생성 > extends HttpServlet 해주고 

shift  + alt + s 해서 do get 오버라이딩

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      
      // 응답 : html 생성해서 반환
      // 응답 관련 객체 : HttpServletResponse response
      
      // 컨텐트 타입과 character set 설정
      response.setContentType("text/html; charset=UTF-8");
      
      // 응답 처리에 사용할 날짜와 시간 데이터
      Date now = new Date();
      
      // HTML의 응답 처리를 위한 스트림 생성
      PrintWriter writer = response.getWriter();
      
      // 응답 데이터를 출력 : html 구조
      writer.println("<html>");
      writer.println("<head><title>now Date</title></head>");
      writer.println("<body>");
      writer.println("<h1>현재시간 : ");
      writer.println(now); // now.toString()
      writer.println("</h1>");
      writer.println("<h1>서블릿에서 생성된 응답코드</h1>");      
      writer.println("</body>");
      writer.println("</html>");
      
      writer.close();
   }
   
}

 

 


 

-서블릿 3.0버전부터는 @WebServlet 이노테이션을 사용하면, 웹 컨테이너가 자동 등록.

  <!-- 
  	서블릿 등록
  	서블릿 이름, 서블릿 클래스의 풀네임  
  -->
  
  <servlet>
  	<servlet-name>nowServlet</servlet-name>
  	<servlet-class>test.HelloServlet</servlet-class>  
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>nowServlet</servlet-name>
  	<url-pattern>/hello</url-pattern>
  </servlet-mapping>

 

 

 

 

정리 ) 위에했던 것

 

 

 

 

톰캣 다운받기

 

tomcat.apache.org/download-80.cgi

 

수업에선 이거 받았음 8.5

 

 

– startup.bat – 톰캣을 독립 프로세스로 시작

– shutdown.bat – 실행된 톰캣을 종료시킨다.

– catalina.bat – 톰캣을 시작하거나 종료한다.

 

 

 

이클립스 기본 환경 설정

 

preferences > server > runtime Environments

에서 add 누르고 tomcat 버전에 맞게 눌러준다.

create a new local server 체크해주고 next

 

 

 

이름 해주고 디렉토리는 톰캣이 설치된 곳으로 잡아준다.

(여기는 C드라이브에 바로 압축 풀었음)

 

 

완료후 옆에 이렇게 생기는 것을 볼 수 있다.

 

 

이클립스 기본 주석 설정하기

 

텍스트 인코딩 설정하기

 

1. [General] → [Workspace] → Text file encoding 항목을 Other 로 변경한 뒤 UTF-8로 설정

2. 자바 클래스 인코딩 설정 : [General] → [Content Types] → Java Class File에 

   대한 Default encoding 값을 UTF-8 로 입력 후 <Update> 버튼

3. JSP 파일 인코딩 설정 : [General]→[Content Types] → [Text] → JSP 항목을 UTF-8 로 변경 후 <Update> 버튼

4. CSS / HTML / JSP 코드 인코딩 설정 : [Web] → [HTML Files], [JSP Files] 항목을 ISO 10646/Unicode(UTF-8)로 변경

 

http://coderap.tistory.com/539

<input type="text" id="pnum" name="pnum" required
onKeyup="this.value=this.value.replace(/[^0-9]/g,'');" />

숫자 이외에 다른 키 입력이 되지 않는다.

 

마우스이벤트

'

 

키보드이벤트

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>제이쿼리 키보드 이벤트</title>
    <!--제이쿼리 라이브러리 로드-->
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

    <style>
    
        .rudrh{
            color:red;
        }
    </style>

    <script>
    
        $('document').ready(function(){
            
            $('textarea').keyup(function(){
                
                //현재 입력 문자열의 길이
                var inputStrLen = $(this).val().length;                
                
                
                if(inputStrLen>50){
                    $('span').addClass('rudrh');
                    alert('50자까지만 입력가능!');                    
                    var userInput = $(this).val().substr(0,50);
                    $(this).val(userInput);
                    userInput = 50;                    
                }else{
                    $('span').removeClass('rudrh');
                }
                
                $('span').text(inputStrLen);
                
            })        
                        
        });
        
    </script>
    
</head>
    
    

<body>
    
    <textarea rows="10" cols="50"></textarea>
    <h1><span>0</span>/50</h1>
    
</body>
</html>

 

 

윈도우이벤트

윈도 이벤트는 윈도 객체만 사용할 수 있는 이벤트가 아니라

window 객체와 document 객체 이외에 img 태그 등이 사용할 수 있는 이벤트

 

 

입력 양식 이벤트

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>체크박스</title>

    <!--jQuery 라이브러리 로드-->
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    
        <script>
        $('document').ready(function(){
           
            // 체크박스 이벤트 처리 : change() 메소드 사용
            $('#check-all').change(function(){
                if(this.checked){
                    $('#check-item').children().prop('checked',true);
                }else {
                    $('#check-item').children().prop('checked',false);
                }
            });
        
            
        });
    </script>
    
</head>

<body>
    
    개인정보활용 동의 <input type="checkbox" id="agree"><br>.
    <input type="checkbox" id="check-all"><label> 전체선택</label>
    <br><br>
    <div id="check-item">
        <input type="checkbox"> 게시물 1 <br>
        <input type="checkbox"> 게시물 2 <br>
        <input type="checkbox"> 게시물 3 <br>
        <input type="checkbox"> 게시물 4 <br>
        <input type="checkbox"> 게시물 5 <br>        
    </div>
</body>

</html>

이벤트를 연결할 때 on ( ) 메서드를 사용

 

 

on( ) 메서드를 사용하지 않은 기본 이벤트 연결

    <script>
        
        $('document').ready(function(){
        
        
           $('h1').click(function(){
               var length = $('h1').length;
               var html = $(this).html();
               
               $('#wrap').append('<h1>'+length+' - '+html+'</h1>');
           });
            
            
        });
    </script>

</head>

<body>


    <div id="wrap">
        <h1> HEADER 1 </h1>
    </div>

 

 

 

- delegate 방식을 사용하는 on( ) 메서드

- 이벤트 리스너에서 this 키워드가 #wrap 태그가 아니라 h1 태그라는 것을 주의

        
        $('document').ready(function(){

            // 범위를 지정하고 해당 범위안의 엘리먼트를 지정해서 이벤트 적용
            // 해당 범위에 특정 엘리먼트가 추가되어도 이벤트를 적용.
           $('#wrap').on('click','h1',function(){
               
               var length = $('h1').length;
               var html = $(this).html();
               
               $('#wrap').append('<h1>'+length+' - '+html+'</h1>');
               
               
           });
            
        });           

 

                // 제거
                $('#wrap').off('click', 'h1');

1) $(this).html($(this).html()+'+');
2) $(this).html(function(index, html){return html+'+'});

1)

    <script>

        $('documnet').ready(function() {

            // 이벤트 연결
            $('h1').on('click',function(){
                
                // 클릭이 발생하면 이벤트가 발생한 객체의 문자열을 변경
                // this는 이벤트가 발생한 객체
                $(this).html($(this).html()+'+');
            });

        });

    </script>

</head>

<body>


    <h1> CLICK1 </h1>

</body>

2)

        $('documnet').ready(function() {
        
            // 이벤트 연결
            $('h1').on('click',function(){
                 $(this).html(function(index, html){                     
                        return html+'+'; 
                 });
            });
        });

둘다 실행 결과는 같다 // 클릭할때 마다 +가 생김

 

 

 

이벤트 연결 

1) 기본


- on ( ) 메서드의 매개변수에 객체를 넣어줌
- 속성 이름과 속성 값에 이벤트 이름과 이벤트 리스너를 넣으면 이벤트를 쉽게 연결

 

        $('documnet').ready(function() {
            
            // 여러개의 이벤트를 등록할 때 객체 형식으로 정의
            $('h1').on({
                mouseenter:function(){
                    $(this).addClass('h1over'); // style에 .h1over만들어놓음
                },
                mouseleave:function(){
                    $(this).removeClass('h1over');
                },
                click : function(){
                    console.log(event);
                    $(this).html(function(index, html){
                        return html + '*'
                    })
                }
            })
            
            
        });

        $('documnet').ready(function(){
            $('h2').hover(function(){
                $(this).addClass('over');       
            }, function(){
                $(this).removeClass('over');
            })
            
        });

 

이벤트 연결 제거

 

- off ( ) 메서드는 다음 형태로 사용
- 1번 형태는 해당 문서 객체와 관련된 모든 이벤트를 제거
- 2번 형태는 해당 문서 객체의 특정 이벤트와 관련된 모든 이벤트를 제거
- 3번 형태는 특정 이벤트 리스너를 제거

        $('documnet').ready(function() {

            // 여러개의 이벤트를 등록할 때 객체 형식으로 정의
            $('h1').on({
                mouseenter: function() {
                    $(this).addClass('over'); // style에 .h1over만들어놓음
                },
                mouseleave: function() {
                    $(this).removeClass('over');
                },
                click: function() {
                    console.log(event);
                    $(this).html(function(index, html) {
                        return html + '*'
                    });
                    $(this).off('click');
                }
            })
        });


        $('documnet').ready(function() {
            $('h2').hover(function() {
                $(this).addClass('over');
            }, function() {
                $(this).removeClass('over');
                $('h2').off();
            })

        });

처음 한번만 실행되고 두번째부터는 실행되지 않는다.

1) hover는 테두리가 처음 한번만 생기고 다음엔 안생김

2) 눌러도 별표 한개이상 안생김

 

 

매개변수 context

- 특정 부분에 선택자를 적용하고 싶을 때 사용하는 것이 매개변수 context

- 매개변수 context는 selector가 적용하는 범위를 한정

    <script>
        $('documnet').ready(function() {

            $('div').click(function(){

                var header = $('h1', this).text();
                var paragraph = $('p', this).text();

                alert(header + ' : ' + paragraph);


            });
        });
    </script>

</head>

<body>

    <div>
        <h1> header - 1 </h1>
        <p> paragraph - 1 </p>
    </div>
    <div>
        <h1> header - 2 </h1>
        <p> paragraph - 2 </p>
    </div>
    <div>
        <h1> header - 2 </h1>
        <p> paragraph - 2 </p>
    </div>
</body>

 

 

이벤트 강제발생

 

        $(document).ready(function() {

            $('h1').on({
                mouseenter: function() {
                    $(this).addClass('over');
                },
                mouseleave: function() {
                    $(this).removeClass('over');
                },
                click: function(event) {
                    console.log(event);
                    $(this).html(function(index, html) {
                        return html + '+';
                    });
                }
            });

            setInterval(function(){
            	// h1의 마지막에 click 이벤트 강제발생
                $('h1').last().trigger('click');
            }, 1000);           
        });

계속해서 +가 발생한다.

 

 

버블링 막기

 

자바스크립트의 버블링에 대해서 알기쉬운 티스토리

http://programmingsummaries.tistory.com/313

 

 

[JavaScript] JavaScript에서 이벤트 전파를 중단하는 네가지 방법

자바스크립트 이벤트 리스너에서 preventDefault() 와 stopPropagation()  그리고 return false 는 자바스크립트 프로그래밍을 할 때 이벤트 중단을 위해 자주 사용되는 코드들이다. 이벤트 중단 시에 사용되

programmingsummaries.tistory.com

 

 

1) 버블링을 막지 않으면 <a>태그부분을 눌러도 div부분의 이벤트(alert)가 같이 실행된 후 네이버로 이동한다.

    </script>
		$('div').click(function() {

                var header = $('h1', this).text();
                var paragraph = $('p', this).text();

                alert(header + ' : ' + paragraph);
            });


            $('a').click(function(event) {
                //event.preventDefault();
                //return false;
            });

        });

    </script>

</head>

<body>
    <div>
        <h1>Header 1</h1>
        <p>paragraph 1</p>

        <h3>
            <a href="http://www.naver.com">네이버</a>
        </h3>

    </div>

</body>

</html>

 

2) preventDefault ( ) 메서드로 a 태그의 기본 이벤트를 제거하면,

 a 태그의 네이버로 이동하는 이벤트는 작동하지 않아서 네이버로 가지지는 않지만,

여전히 div의 이벤트인 alert는 작동한다.

 

            $('a').click(function(event) {
                event.preventDefault();
                //return false;
            });

 

 

 

 

3) return false;를 해주면 <a>태그 네이버를 눌러도 아무런 일도 일어나지 않는다.

return false

stopPropagation ( ) 메서드와 preventDefault ( ) 메서드를 함께 사용하는 경우가 많으므로, 

jQuery는 간단하게 return false를 사용하면 이 두 가지를 함께 적용하는 것으로 인식

            $('a').click(function(event) {
                //event.preventDefault();
                return false;
            });

 

 

 

 

1) appendTo

 

문서 객체 생성 , 문서 객체 연결

    <script>
        $(document).ready(function() {

            $('input[type=button]').click(function(){
                
                
                $('<h1></h1>').html('<i>새로운 태그 추가</i>').appendTo('div');
                
            });
            
        });
    </script>
</head>

<body>

    <div></div>
    
    <input type="button" value="동적tag추가">

</body></html>

더보기

이런 경우(아래코드)에는 생성 시점이 달라서 글씨색이 변경되지 않고 그냥 나온다.

- 코드가 같은 {} 곳에 삽입되어있다면 버튼을 누르면 원래 글씨색은 검정에서 빨간색으로 바뀌고,

  새로운 태그 추가부터 블루 초록 빨강 이런식으로 나옴

 

    <script>
        $(document).ready(function() {

            $('input[type=button]').click(function() {

                $('<h1></h1>').html('<i>새로운 태그 추가</i>').appendTo('div');

                //            var h1='<h1>안<h1>';
                //            var h2='<h1>녕<h1>';
                //            var h3='<h1>하<h1>';
                //            var h4='<h1>세<h1>';
                //            var h5='<h1>요<h1>';
                //            
                //            $('div').append(h1, h2, h3, h4, h5);

            });

        });

        $(document).ready(function() {
            var colors = ['red', 'blue', 'green'];

            $('h1').css('color', function(index) {
                return colors[index];
            });
        });
        
    </script>

</head>

<body>

    <div>
        <h1>원래있던태그</h1>
    </div>

    <input type="button" value="동적tag추가">

</body></html>

 

 

 

텍스트 노드를 갖지 않는 문서 객체를 생성하는 방법

- img 태그를 생성할 때는 $ ( ) 메서드로 문서 객체를 생성하고 attr ( ) 메서드로 속성을 입력

 

        $(document).ready(function() {

        $('input[type=button]').click(function(){
        
        $('<img>').attr({
        src:'../tae6.jpg',
        height:100
        }).appendTo('div');

        });

        });

 

 

2) append

- append ( ) 메서드의 사용 형태

 

- 여러 개의 문서 객체를 한꺼번에 입력할 수 있음

        $('input[type=button]').click(function(){

            var h1='<h1>안<h1>';
            var h2='<h1>녕<h1>';
            var h3='<h1>하<h1>';
            var h4='<h1>세<h1>';
            var h5='<h1>요<h1>';
            
            $('div').append(h1, h2, h3, h4, h5);
        });

- 배열을 사용한 문서 객체 생성과 추가

    <script>
        $(document).ready(function() {

            $('input[type=button]').click(function() {

                var links = [
                    {name:'네이버', url:'http://www.naver.com'},
                    {name:'다음', url:'http://www.daum.net'},
                    {name:'구글', url:'http://www.google.com'},
                ];
                
                $('h1').append(function(index){
                    var item = links[index];
                    var output = '<a href="'+item.url+'">'+item.name+'</a>';
                    
                    return output;
                    
                });

            });

        });
    </script>

</head>

<body>

    <div>
        <h1> 네이버 </h1>
        <h1> 카카오 </h1>
        <h1> 페이스북 </h1>
    </div>

    <input type="button" value="동적tag추가">

</body></html>

 

3) 문서 객체 이동

    <script>
        $(document).ready(function(){
           
            setInterval(function(){
                // 첫번째 이미지를 마지막으로 보낸다.
                 $('img').first().appendTo('div');
            },2*1000);
            
            
            
        });
    </script>
    <style>
        
        div {
            width: 150px;
            height: 150px;
            
            border: 2px solid black;
            
            overflow: hidden;
        }
        img {
            width: 150px;
            height: 150px;
        }
    </style>

</head>

<body>

    <div>
        <img src="/image/tae1.jpg">
        <img src="/image/tae2.jpg">
        <img src="/image/tae3.png">
        <img src="/image/tae4.jpg">
        <img src="/image/tae5.jpg">
    </div>

</body></html>

 

 

1) 문서 객체의 내부 검사

    <script>
        $(document).ready(function() {
            //html( ) 메서드 - Getter
            console.log('div->', $('div').html());
            //text( ) 메서드 - Getter
            console.log('div->', $('div').text());
        });
    </script>

</head>

<body>

    <div>

        <h1> 네이버 </h1>
        <h1> 카카오 </h1>
        <h1> 페이스북 </h1>

    </div>

 

2) 문서 객체의 내부 추가

            $('button').first().click(function() {
                $('div>h1').html('<h4>html</h4>');
            });

            $('button').first().click(function() {
                $('div>h1').text('<h4>text</h4>');
            });

 

 

 

            $('button').first().click(function() {
                $('div>h1').html(function(index){
                    return '<h'+(index+2)+'>안녕!</h'+(index+2)+'>';            
                });

            $('button').first().click(function() {
                $('div>h1').text(function(index){
                    return '<h'+(index+2)+'>안녕!</h'+(index+2)+'>';            
                });              
            });

 

3) 문서 객체 제거

            $('button').first().click(function() {
                $('div').empty();
            });

            $('button').first().click(function() {
                $('div>h1:first').remove();
            });

+ Recent posts