【问题标题】:JQuery - get .html() after having set with .html()JQuery - 使用 .html() 设置后获取 .html()
【发布时间】:2011-12-03 00:55:03
【问题描述】:

我正在使用具有 localStorage 功能的 jQuery。

这是我所拥有的:

<textarea name="localStorageString" id="localStorageString"></textarea>
<script>
  var userJson = localStorage.getItem('userJson');
  $('#localStorageString').html(userJson);
  $('#localStorageString').keyup(function(){
    alert($(this).html());
});

textarea 填写正确,问题是当我修改它时,它总是提示相同的值(由html(userJson) 设置)。

有什么想法吗?

【问题讨论】:

    标签: javascript jquery local-storage


    【解决方案1】:

    您需要$(this).val() 来获取表单元素的值。

    【讨论】:

      【解决方案2】:

      我忘记了这个。为什么.html() 不起作用?

      html() - 它是原生 JavaScript .innerHTML 函数。它将标签内的所有内容(所有节点)作为字符串。

      <div id="Node">
         <a href="#">Hello</a>
      </div>
      console.info($('#Node').html()); // <a href="#">Hello</a>
      

      val() - 那是form.element.value

      【讨论】:

      • 好的。但是在文本区域的情况下,为什么结果不一样?
      • 它的 jQuery API。我想它为您提供了对表单元素及其值的统一访问。真的很有道理。
      【解决方案3】:

      不要使用html(),使用val()

      【讨论】:

        【解决方案4】:

        简单:不要在&lt;textarea&gt;(或其他表单元素)上使用.html()。使用.val()(或.value)。

        $('#localStorageString').val(userJson)
        .keyup(function() {
            console.log(this.value);
        });
        

        http://jsfiddle.net/mattball/Zz2cF/

        【讨论】:

          【解决方案5】:

          尝试使用.val() 而不是.html()

          .val():http://api.jquery.com/val

          .html():http://api.jquery.com/html

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-10
            • 1970-01-01
            • 2012-11-29
            • 1970-01-01
            相关资源
            最近更新 更多