비전공자 개발일기

Conditional Statements in jQuery 본문

JQuery

Conditional Statements in jQuery

HiroDaegu 2022. 1. 8. 19:13
728x90
SMALL

HTML 코드
조건에 따른 코드 추가

특정 클래스 존재 유무에 따른 jQuery 실행문 예시

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Conditional Statements  in jQuery</title>
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4544051457126963"
     crossorigin="anonymous"></script>
  <style>
    
      .container {
        text-align: center;
        width: 200px;
        height: 200px;
        border: 1px solid;
      }

      .box0 {
        width: 50px;
        height: 50px;
        background-color: red;
        text-align: center;
        line-height: 50px;
      }

      .box1 {
        width: 50px;
        height: 50px;
        background-color: orange;
        text-align: center;
        line-height: 50px;
      }

      .box2 {
        width: 50px;
        height: 50px;
        background-color: royalblue;
        text-align: center;
        line-height: 50px;
      }

      .box3{
        width: 50px;
        height: 50px;
        background-color: green;
        text-align: center;
        line-height: 50px;
      }
  </style>
</head>
<body>
  <div class="container">
    <div class="box1">BOX1</div>
    <div class="box2">BOX2</div>
    <div class="box3">BOX3</div>
  </div>
</body>
<script>
$(function() {
  let code = "<div class=box3>BOX3</div>"
  let code2 = "<div class=box0>BOX0</div>"
  if(!$("div").hasClass("box3")) {
    $(".container").append(code);
  } else {
    $(".box1").before(code2)
  }
});
</script>
</html>
728x90
LIST

'JQuery' 카테고리의 다른 글

Read More & Read Less Button  (0) 2022.05.08
Dynamic Select Option  (0) 2022.05.04
JQuery - input & button Event  (0) 2022.01.05
JQuery - sortable  (0) 2021.12.27
JQuery 17 - datepicker  (0) 2021.12.24