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

如何在悬停关联label时获取对应的input元素值?

悬停label获取对应input值的解决方案

你的HTML结构中,label的for属性与对应input的id一一绑定,这是关联两者的核心依据。可以按以下方式修改你的jQuery代码来实现需求:

jQuery(".rating__label").hover(
  function(){
    // 获取当前label绑定的input的id
    const targetInputId = jQuery(this).attr("for");
    // 通过id找到对应input并获取其value
    const inputValue = jQuery(`#${targetInputId}`).val();
    console.log(`input value='${inputValue}'`);
  },
  function(){
    console.log("unhovered");
  }
);

代码说明:

  • jQuery(this):在悬停回调里,this指向当前触发事件的label元素,用jQuery包装后可调用其方法。
  • .attr("for"):提取当前label的for属性值,该值就是关联input的唯一id。
  • jQuery(#${targetInputId}):用模板字符串拼接id选择器,精准定位到对应的input元素。
  • .val():获取目标input的value属性值。

如果不想依赖jQuery,也可以用原生JavaScript实现:

document.querySelectorAll(".rating__label").forEach(label => {
  // 鼠标进入事件
  label.addEventListener("mouseenter", function() {
    const input = document.getElementById(this.getAttribute("for"));
    console.log(`input value='${input.value}'`);
  });
  // 鼠标离开事件
  label.addEventListener("mouseleave", function() {
    console.log("unhovered");
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:30:18