You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定JavaScript重置函数转为jQuery函数及相关疑问解答

问题解答

1)将原生JavaScript重置函数转换为jQuery版本

我把原生JS的reset函数转换成jQuery版本了,代码如下,每一步都对应原生逻辑:

function reset() {
  // 获取第一个.custom-select的jQuery对象
  const $customSelect = $(".custom-select:first");
  // 查找内部的select元素
  const $select = $customSelect.find("select");
  // 找到显示选中状态的元素
  const $selected = $customSelect.find(".select-selected");
  // 找到当前标记为选中的选项元素
  const $selectedItem = $customSelect.find(".same-as-selected");

  // 重置select的选中索引为0
  $select.prop("selectedIndex", 0);
  // 更新显示的选中文本为第一个选项的内容
  $selected.html($select.find("option:eq(0)").html());
  // 移除选中项的样式类
  $selectedItem.removeClass("same-as-selected");
}

简单对应说明:

  • 原生的document.getElementsByClassName("custom-select")[0] → jQuery的$(".custom-select:first")(直接获取第一个匹配元素的jQuery包装对象)
  • 原生的getElementsByTagName/ClassName查找后代 → 用jQuery的.find()方法更简洁
  • 原生的selectedIndex属性设置 → 用jQuery的.prop()方法操作DOM元素属性
  • 原生的innerHTML设置 → 用jQuery的.html()方法
  • 原生的classList.remove → 用jQuery的.removeClass()方法

2)为什么输出结果不同?

这个差异的核心是原生DOM元素对象和jQuery对象的本质区别,以及你调用的方法不一样:

  • 原生代码里document.getElementsByClassName("custom-select")[0]返回的是一个真实的DOM元素对象(这里是HTMLDivElement类型),当你直接打印它时,浏览器会输出它的对象类型标识[object HTMLDivElement]。
  • 而你写的jQuery代码$(".custom-select:eq(0)").html(),首先$(".custom-select:eq(0)")是包含该DOM元素的jQuery包装对象,但你立刻调用了.html()方法——这个方法的作用是获取元素内部的HTML源代码,所以输出的是这个div里面的所有HTML内容。

如果想让jQuery部分也输出和原生一样的对象标识,你可以这样写:

var jqcustomSelect = $(".custom-select:eq(0)");
console.log(customSelect + " JQ: " + jqcustomSelect[0]);

这里jqcustomSelect[0]是从jQuery对象中取出对应的原生DOM元素,打印出来就会和原生的结果一致了。

内容的提问来源于stack exchange,提问作者Fjott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:52:43