迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中如果元素存在,则调用函数

作者:迹忆客 最近更新:2022/12/31 浏览次数:

如果元素存在则调用函数:

  1. 使用 getElementByIdquerySelector 方法来选择元素。
  2. 检查存储的值是否不等于 null。
  3. 如果满足条件,则调用该函数。

以下是本文示例的 HTML。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box">Box content</div>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

function sum(a, b) {
  return a + b;
}

// ✅ Select element by ID [getElementById]
const el1 = document.getElementById('box');

if (el1 !== null) {
  console.log(sum(5, 55));
  console.log('✅ el1 exists');
} else {
  console.log('⛔️ el1 does NOT exist');
}

// ✅ Select the first element with class [querySelector]
const el2 = document.querySelector('.my-class');

if (el2 !== null) {
  console.log(sum(5, 55));
  console.log('✅ el2 exists');
} else {
  console.log('⛔️ el2 does NOT exist');
}

在我们的第一个示例中,我们使用 document.getElementById 方法通过 id 选择元素。

该方法返回元素,其 id 属性与提供的字符串匹配。

如果文档中不存在具有提供的 id 的元素,则返回 null 值。

我们的 if 语句在调用 sum 函数之前检查存储在 el1 变量中的值是否不等于 null。

if 块仅在元素存在时运行,否则运行 else 块。

在第二个示例中,我们使用 document.querySelector 方法获取与提供的选择器匹配的第一个元素。

function sum(a, b) {
  return a + b;
}

// ✅ Select the first element with class [querySelector]
const el2 = document.querySelector('.my-class');

if (el2 !== null) {
  console.log(sum(5, 55));
  console.log('✅ el2 exists');
} else {
  console.log('⛔️ el2 does NOT exist');
}

querySelector 方法将表示有效 CSS 选择器的字符串作为参数。

如果没有元素与选择器匹配,该方法将像 getElementById 方法一样返回空值。

页面上没有类为 my-class 的元素,因此不满足条件,运行 else 块。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便