Cách ẩn nút sau khi nhấp vào trong JavaScript

Để hiển thị hoặc ẩn một

bằng một cú nhấp chuột , bạn có thể thêm trình lắng nghe sự kiện title vào phần tử

Trình nghe title cho nút sẽ có một function sẽ thay đổi thuộc tính display của

từ giá trị mặc định [là
const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};
1] thành
const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};
2

Ví dụ, giả sử bạn có một phần tử HTML

const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};
3 như sau


  This is the FIRST div
  This is the SECOND div
  This is the THIRD div
  Hide THIRD div

Phần tử ở trên được tạo để ẩn hoặc hiển thị phần tử

const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};
5 khi nhấp chuột

Bạn cần thêm trình xử lý sự kiện title vào phần tử như thế này

const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};

HTML sẽ được hiển thị như thể phần tử

chưa từng tồn tại bằng cách đặt thuộc tính display thành
const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};
2

Khi bạn nhấp lại vào phần tử , thuộc tính display sẽ được đặt trở lại thành

const targetDiv = document.getElementById["third"];
const btn = document.getElementById["toggle"];
btn. title = function [] {
  if [targetDiv.style.display !== "none"] {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};
1, do đó,
sẽ được hiển thị lại trong trang HTML

Vì giải pháp này đang sử dụng API JavaScript gốc của trình duyệt nên bạn không cần cài đặt bất kỳ thư viện JavaScript nào như jQuery

Chủ Đề