【问题标题】:Jquery, variable undefinedJquery,变量未定义
【发布时间】:2013-06-24 11:11:37
【问题描述】:

所以我得到了这个小代码,但我无法让它工作,我根本不明白为什么。我从我编写的另一个代码中复制了代码,只删除并重命名了所有我不需要的东西。我想在警告框中给出变量的值。

JS:

<script>
     function ready2() {
         var rdy = $("#rdy").value;
         alert(rdy); 
     }
</script>

HTML:

<body>
   <form id="form2" onsubmit="return false;">
      <div>Ready:</div>
      <input type="text" id="rdy"></input>
      <button id="btn" onclick="ready2()">Ready</button>
   </form>
</body>

如果我将$("#rdy").value; 替换为“hello world”之类的内容,它会起作用。所以问题一定是变量或者更好的:输入框。警告框总是显示“未定义”,我不知道为什么。

有什么帮助吗?

【问题讨论】:

    标签: jquery variables undefined


    【解决方案1】:

    你需要这个 -

    var rdy = $("#rdy").val();
    

    var rdy = $("#rdy")[0].value;
    

    您只能在 DOM 元素上使用 value,因为您在 jquery 对象上使用它,所以您会变得未定义,即 - $("#rdy")

    【讨论】:

      【解决方案2】:

      当你这样做时:

      $("#rdy")
      

      您实际上是在生成一个包含所有节点的 jQuery 对象数组:

      [domNode1, domNode2,... domNodeN] 
      //note this array is a jQuery object, not an Array
      

      因为它是一个 ID,它应该只能找到一个:

      [domNodeWithIdrdy]
      

      jquery 数组内的 DOM 节点和getElementById 一样,这意味着你可以直接访问这些值:

      var jArray = $("#rdy");
      console.log(jArray[0].value);
      

      jQuery 还提供了一些功能来做到这一点:

      $("#rdy").value();
      

      但请记住,val() 函数只会返回 jquery 数组中第一个元素的值,而忽略数组中存在的多个元素。

      使用.val() 也比使用jArray[0].value 更安全。这是因为如果数组为空,它将尝试从undefined 中读取value。即:

      jArray = $("#somethingThatDoesntExist");
      assert( jArray.length === 0 );
      assert( jArray[0] === undefined );
      

      【讨论】:

      • .val() 不是.value()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2021-11-19
      • 2015-08-21
      相关资源
      最近更新 更多