为什么我用 jquery.val() 得到“未定义”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3142948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:54:40  来源:igfitidea点击:

Why am I getting "undefined" with jquery.val()?

jqueryundefined

提问by dcp3450

Goal: read in the current value of a set of text boxes. if the value is "None" replace the value with the value provided. Once a value is changed stop.

目标:读入一组文本框的当前值。如果值为“无”,则用提供的值替换该值。一旦值改变停止。

When I use span and .text() instead of a textbox and .val() everything works. However, the textboxes are part of a form.

当我使用 span 和 .text() 而不是文本框和 .val() 时,一切正常。但是,文本框是表单的一部分。

Any idea why it would return as "undefined"?

知道为什么它会返回为“未定义”吗?

(basically i'm making a list from user input)

(基本上我正在根据用户输入制作一个列表)

html:

html:

<input type="text" name="class1" value="None" ><br>
<input type="text" name="class2" value="None" ><br>
<input type="text" name="class3" value="None" ><br>
<input type="text" name="class4" value="None" ><br>
<input type="text" name="class5" value="None" ><br>

jquery:

查询:

function compareClass(a)
   {
      var input = a;
      for(x=1;x<6;x++)
      {
         var classText = $('.class'+x).val();
         if(classText == "None")
         {
            $('.class'+x).val(input);
            break;
         }
      }      
   }

回答by Pekka

You are telling jQuery to look for elements with classclass[x]but you are assigning names.

您告诉 jQuery 查找具有class 的元素,class[x]但您正在分配names。

You could change the nameproperties to ids:

您可以将name属性更改为ids:

<input type="text" id="class1" value="None" ><br>
<input type="text" id="class2" value="None" ><br>
<input type="text" id="class3" value="None" ><br>
<input type="text" id="class4" value="None" ><br>
<input type="text" id="class5" value="None" ><br>

and fetch by ID:

并通过 ID 获取:

var classText = $('#class'+x).val(); // Note the #!

(obviously, "class" won't make any sense now as a name probably)

(显然,“类”现在作为名称可能没有任何意义)

Alternatively, you could in fact use the classproperty but CSS classes can be be assigned to multiple elements, so it's not really suitable here.

或者,您实际上可以使用该class属性,但可以将 CSS 类分配给多个元素,因此它在这里不太适合。

回答by James Westgate

Use selectors in jQuery to simplify your code. [name^=Class]means all inputs with a nameattribute starting with Class(Quotes not required)

在 jQuery 中使用选择器来简化您的代码。[name^=Class]表示具有nameClass(不需要引号)开头的属性的所有输入

function compareClass(a)
{
  $('input [name^=Class]').each(function() {

     if ($(this).val() === 'None') $(this).val(a);

  });
}