본문 바로가기

학원/Java Script

17_Javascript 활용

728x90
반응형

글자 제한 함수

function checkLength() {
    var textarea = document.querySelector("[name=q1]");
    var span = document.querySelector("[name=q1]+span");

    var len = textarea.value.length;
    span.textContent = len;

    while (len > 1000) {
      textarea.value = textarea.value.substring(0, textarea.value.length - 1);
      len--;
    }
}

생성자

//일회용 객체 생성
var a = { name: "피카츄", score: 90 };
//생성자 함수 사용
function Student(name, score) {
    this.name = name;
    this.score = score;
    this.setName = function (name) {
      this.name = name;
    };
    this.getName = function () {
      return this.name;
    };
}
//함수표현식
var c = function () {
    console.log("hello");
};
//함수선언
function d() {
    console.log("Hello");
}
//멤버메서드 : 함수가 변수처럼 보관되면서 메서드처럼 사용 가능
var stu = {
    name: "피카츄",
    score: 99,
    setName: function (name) {
      this.name = name;
    },
    getName: function () {
      return this.name;
    },
    setScore: function (score) {
      this.score = score;
    },
    getScore: function () {
      return this.score;
    },
};

독립형 자바스크립트 템플릿

window.onload = function () {
    var button = document.querySelector("button");
    button.onclick = function () {
      console.log("hello");
    };
};

window.addEventListener("load", function () {
    var button = document.querySelector("button");

    button.addEventListener("click", function () {
      console.log("hello");
    });
});
//같은 클래스를 사용하는 여러 elements 사용
window.addEventListener("load", function () {
    var buttons = document.querySelectorAll(".color-btn");
    for (var i = 0; i < button.length; i++) {
      buttons[i].addEventListener("click", function () {
        var target = document.querySelector("#target");
        //this는 이벤트가 발생한 주인공 태그 객체를 의미한다
        target.style.color = this.dataset.color;
      });
    }
});

a태그 onclinck 제어

document
  .querySelector(".confirm-link")
  .addEventListener("click", function (e) {
    var choice = window.confirm("정말 이동하시겠습니까?");
    if (!choice) e.preventDefault();
  });
});
728x90
반응형

'학원 > Java Script' 카테고리의 다른 글

16_Javascript 기본  (0) 2023.03.06