【Javascript】Day6:JavaScript in the Browser: DOM and Events Fundamentals

文章介绍了DOM(文档对象模型)的概念,它是HTML文档与JavaScript交互的桥梁。通过示例展示了如何使用DOM方法选择和操纵元素,如textContent和value属性。此外,文章还涉及了事件监听,如click事件,以及如何处理键盘事件。同时,文章提到了代码优化,如DRY原则,以及通过类来管理CSS样式。最后,讨论了如何处理多个事件监听器和响应ESC键事件。
摘要由CSDN通过智能技术生成

What’s the DOM and DOM Manipulation

DOM: Document Object Model, a structrued representation of HTML documents.

DOM is basically a connection point between HTML documents and JavaScript code.
what

The DOM really is a complete representation of the HTML document.
DOM tree

JS is just a dialect of the ECMAScript specification

The DOM and DOM methods are actually part of something called the web APIs.

DOM&JS

Selecting and Manipulating Elements

// textContent
console.log(document.querySelector('.message').textContent);
document.querySelector('.message').textContent = '🎉Correct Number!';

document.querySelector('.number').textContent = 13;
document.querySelector('.score').textContent = 10;

// value
document.querySelector('.guess').value = 23;
console.log(document.querySelector('.guess').value);

res

Handling Click Events

event listener: our code reacts to something that happens in the DOM. With it, we can wait for a certain event to happen and the react to it

An event is something that happens on the page, for example, a mouse click or a mouse moving or a key press.

// addEventListener(): listen for events in JavaScript
// argument: type of the event; event handler(tell the event listener want to do) a function value
document.querySelector('.check').addEventListener('click', function () {
  const guess = Number(document.querySelector('.guess').value);
  console.log(guess, typeof guess);

  if (!guess) {
    document.querySelector('.message').textContent = '⛔ No number';
  }
});

res

Manipulating CSS Styles

else if (guess === secretNumber) {
    document.querySelector('.message').textContent = '🎉Correct Number!';
    // whenever manipulating a style, we always need to specify a string
    // inline styles
    document.querySelector('body').style.backgroundColor = '#60b347';
    document.querySelector('.number').style.width = '30rem';
  }

res

Refactoring Our Code: The Dry Principle

const displayMessage = function (message) {
  document.querySelector('.message').textContent = message;
};

if(guess is right){}
else {
    if (score > 1) {
      //   document.querySelector('.message').textContent = guess > secretNumber ? '📈 Too high!' : '📉 Too low!';
      displayMessage(guess > secretNumber ? '📈 Too high!' : '📉 Too low!');
      score--;
      document.querySelector('.score').textContent = score;
    } else {
      //   document.querySelector('.message').textContent = '🤡 You lost the game!';
      displayMessage('🤡 You lost the game!');
      document.querySelector('.score').textContent = 0;
    }
  }

Another Project

const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnCloseModal = document.querySelector('.close-modal');

// the limitation of querySelector() Method: use a querySelector which matches multiple elements, only the first one will be get selected
// const btnsShowModal = document.querySelector('.show-modal');

// type of btnsShowModal: Nodelist, like an array
const btnsShowModal = document.querySelectorAll('.show-modal');
console.log(btnsShowModal);

for (let i = 0; i < btnsShowModal.length; i++) {
  console.log(btnsShowModal[i].textContent);
}

res

Working With Classes

we can aggregate all of the properties that we need in one class in CSS file, then in JS file we simply add or remove these classes as needed.

When need to manipulate styles on a page, then always just export the styles into a class, just use the class in JS file.

Same function For Multiple Listeners

if the same function is used in multiple event listeners, we can specify the function as a separate function, then pass the function as an argument to multiple ‘addEventListener’ methods.

const openModal = function () {
  console.log('Button clicked');
  // add and remove classes
  modal.classList.remove('hidden');
  overlay.classList.remove('hidden');
};

const closeModal = function () {
  modal.classList.add('hidden');
  overlay.classList.add('hidden');
};

for (let i = 0; i < btnsShowModal.length; i++) {
  //   console.log(btnsShowModal[i].textContent);
  btnsShowModal[i].addEventListener('click', openModal);
}

// not calling the function
// btnCloseModal.addEventListener('click', closeModal()):call the function immediately as soon as JS executes this line
btnCloseModal.addEventListener('click', closeModal);
overlay.addEventListener('click', closeModal);

Handling An “ESC” Keypress Event

how to respond to keyborad events

Keyborad events are so-called global events because they do not happen on a specific element.

For the global event, we usually list an underwhole(?) document

3 types of events for the keyboard: the key down, the key press, or the key up

the information of which key was pressed will be stored in the event that is going to occur as soon as any key is pressed. And anytime that an event like this occurs, JS in fact generate an object which contains all the information about the event itself, and we can access that object in the event handler function

函数名带括号是函数调用,直接执行函数;不带括号是事件绑定,事件触发再执行

document.addEventListener('keydown', function (e) {
  console.log(e.key);

  // check if an element already has a certain class
  if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
    closeModal();
  }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"JavaScript engine fundamentals: Shapes and Inline Caches" 是指JavaScript引擎的基本概念:Shapes(形状)和Inline Caches(内联缓存)。 1. Shapes(形状):在JavaScript引擎中,每个对象都有一个形状,用于描述对象的结构和属性。形状包含对象的属性名称、偏移量和其他相关信息。当创建一个新对象时,引擎会根据对象的属性来确定其形状,并将该形状与对象关联起来。这样,在后续对同一形状的对象进行操作时,引擎可以更高效地执行。 形状对于优化JavaScript代码的执行非常重要。引擎可以根据对象的形状来进行内存布局和属性访问的优化,提高代码的执行效率。如果对象的形状发生变化(例如添加或删除属性),引擎会为该对象创建一个新的形状,并相应地调整相关操作。 2. Inline Caches(内联缓存):内联缓存是一种用于加速函数调用和属性访问的技术。当使用JavaScript代码调用函数或访问对象属性时,引擎会在编译阶段生成内联缓存,将函数调用或属性访问与特定的对象关联起来。 内联缓存可以避免每次函数调用或属性访问时都进行动态查找和解析。引擎会根据对象的形状和属性的特征,将函数调用或属性访问的地址直接嵌入到代码中。这样,在后续对同一对象进行函数调用或属性访问时,引擎可以直接使用内联缓存中的地址,避免了额外的查找和解析开销。 通过使用Shapes和Inline Caches,JavaScript引擎可以提高代码的执行效率和性能,加快函数调用和属性访问的速度。这些基本概念是JavaScript引擎优化和执行的关键部分。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值