【问题标题】:Why is the `value` attribute empty whereas the `value` property has the correct value?为什么 `value` 属性为空,而 `value` 属性具有正确的值?
【发布时间】:2013-12-15 13:34:46
【问题描述】:

我有一个input 字段,它将缓存其value 属性。示例:

$("#signUpEmail").keyup(function(e) {
  console.log(e.target.value); // Works
  console.log($(this).attr("value")); // Doesn’t work
});

如果我将它们都记录在控制台中,e.target.value 将返回我的 input 字段,但不会返回 $(this).attr("value")。谁能解释这是为什么?

【问题讨论】:

标签: javascript html dom html-input


【解决方案1】:

能解释一下为什么会这样吗?

e.target.value 访问 DOM 属性,它始终表示输入字段的当前值。

另一方面,$(this).attr("value") 访问 HTML 属性,这是在 HTML 标记中指定的输入值。当用户更改值时,它不会更新。

您可以使用 $(this).prop('value') 通过 jQuery 访问该属性,但如前所述,.val 是执行此操作的常用方法。

【讨论】:

    【解决方案2】:
    $(this).attr("value"); //can access only default value
    

    例如,

    <input type="text" id="signUpEmail" value="email"/>
    $(this).attr("value"); //returns email
    

    改为使用 prop()

     $(this).prop("value"); //for getting dynamic values
    

    例如:

    <input type="text" id="signUpEmail" />
    $(this).prop("value"); //returns whatever you press
    $(this).attr("value"); //returns undefined
    

    【讨论】:

      【解决方案3】:

      您正在获取值 attribute,它表示 默认 值而不是 当前 值。

      使用val() 方法代替attr()

      $(this).val()
      

      【讨论】:

        【解决方案4】:

        在 jQuery 中获取输入字段的文本使用:

        $(this).val();
        

        对于标签:

        $(this).text();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-07-14
          • 1970-01-01
          • 2018-05-24
          • 1970-01-01
          • 1970-01-01
          • 2017-10-11
          • 2019-06-20
          • 1970-01-01
          相关资源
          最近更新 更多