1

我有 3 个字段:

<input type="datetime" name="input-data" id="datetime-start">
<input type="datetime" name="input-data" id="datetime-end">
<input type="text" name="input-data" id="text-basic">

而且我需要检查是否输入了某些内容,所以我首先喜欢它jQuery.each('[name="input-data"]', function()this在循环中使用,但会出现一些错误。经过小调试后,我找到了类似的方法jQuery.each(jQuery('[name="input-data"]'), function(key, value),但是当我尝试这样做时,console.log(value.val());我得到了错误。所以我决定看看里面有什么value,很惊讶——只有一根绳子<input type="datetime" name="input-data" id="datetime-start">。那么我如何循环遍历所有输入值?

4

5 回答 5

2

You use each on a jQuery instance, e.g.:

jQuery('[name="input-data"]').each(function() {
    // Here, `this` is the DOM element. If you want to use jQuery methods,
    // wrap the element in a jQuery instance:
    var input = jQuery(this);

    // Now, input.val() will give you the value
});

jQuery's API is sometimes a bit confusing. This is one of those times. jQuery has two similar but different functions: The each you call on jQuery instances (see above), and jQuery.each, which you can use to loop through arrays, objects, and array-like objects.

Your code using jQuery.each(jQuery('[name="input-data"]', function... does work, because jQuery instances are array-like, but then within the function you weren't wrapping the DOM element, which is why val() didn't work. But the above is the normal way to loop through a set of matched elements.

于 2013-03-15T08:10:49.480 回答
0

Try

$('input[name="input-data"]').each(function(el){
    console.log($(this).val());
})

Demo: Fiddle

于 2013-03-15T08:11:01.863 回答
0
$(document).ready(function(){
   $('input').each(function(){
     console.log($(this).val());
    });
    }
});
于 2013-03-15T08:11:41.087 回答
0

你使用.each()不正确。尝试这个:

jQuery('[name="input-data"]').each(function() {
    // Use $(this) to access current object
});
于 2013-03-15T08:12:33.430 回答
-1

您正在研究 HTML5,不是吗?为什么不使用给定的 html5 验证?只需设置属性“required='true'”就可以了;-)

在 jquery mobile 中也有一个很好的方法来做到这一点。如果我没记错的话,您必须将“必需”类设置为所需的输入属性。以供参考:

http://www.raymondcamden.com/index.cfm/2012/7/30/Example-of-form-validation-in-a-jQuery-Mobile-Application

于 2013-03-15T08:13:07.557 回答