seong

JS - JQuery(사용법) 요소 삭제,추가, Value값 가져오기 본문

JavaScript/JS

JS - JQuery(사용법) 요소 삭제,추가, Value값 가져오기

hyeonseong 2022. 9. 14. 15:43

JQuery 참고 사이트 

https://www.w3schools.com/jquery/jquery_get_started.asp

 

jQuery Get Started

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

JQuery CDN을 통해 사용

아래 코드를 header사이에 붙여 넣어준다

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

익명함수( 람다식 ) () =>{}

어차피 실행 될 함수 라면 굳이 이름을 만들지 않고 익명 함수로 해줘도 된다. 

<body>
<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>

<script>

// 원래 함수 
// $("#fade").click(function(){
//     $("p").fadeOut();
// });

// 익명 함수로 변형
$("#fade").click(()=>{
    $("p").fadeOut();
});

  $("#hide").dblclick(() => {
    $("p").hide();
  });
  </script>
  </body>

Get Content , Set Content : .val()

username에 있는 value값 가져오기 .val()

<input type = "text" value = "ssar" placeholder="Enter username" id = "username"/>
<script>
    console.log($("#username").val());
</script>

password에 value 값 넣어주기  .val()

   <input type = "text" value = "" placeholder="Enter username" id = "password"/>
   <script>
   $("#password").val("1234");
   </script>

 

삭제 .remove() 

<div class="box">
        <div class= "item" id = "item-1">1</div>
</div>

<script>
// 박스 전체를 날리는 것 - remove
$("#item-1").remove();
</script>

비우기 .empty()

    <div class="box">
        <div class= "item" id = "item-2">2</div>
    </div>
        <script>
        // 박스 안의 내용만 날리는 것 - empty
        $("#item-2").empty();
    </script>

.prepend()

자식을 가장 위로 보낸다 Ex) 가장 최근 쓴 댓글을 제일 위로 보낸다. 

    <div class="box">
        <div class= "item">1</div> 
    </div>
    
        <script>
            //append Ex)가장 최근 쓴 글을 가장 아래로
        $(".box").prepend(getItem(2));
        $(".box").prepend(getItem(3));
        </script>

2가 먼저 들어가고 3이 들어감.

.append()

자식을 가장 아래로 보낸다. Ex) 가장 최근 쓴 댓글을 아래로 보낸다.

    <div class="box">
        <div class= "item">1</div> 
    </div>
    
        <script>
            //append Ex)가장 최근 쓴 글을 가장 아래로
        $(".box").append(getItem(4));
        $(".box").append(getItem(5));
        </script>

4가 먼저 들어가고 5가 들어감.

.before()

부모를 기준으로 위에 추가

    <div class="box">
        <div class= "item">1</div> 
    </div>
    
        <script>
        //박스(부모) 기준으로 위
        $(".box").before(getItem(5));
        $(".box").before(getItem(6));
        </script>

.after()

부모를 기준으로 아래에 추가 

    <div class="box">
        <div class= "item">1</div> 
    </div>
    
        <script>
        //박스(부모) 기준 아래
        $(".box").after(getItem(7));
        $(".box").after(getItem(8));
        </script>