2013-03-15 51 views
1

我有3個領域:如何在jQuery移動中循環元素?

<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"> 

,我需要檢查是否有東西進入,所以我firsly做到了像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">。那麼我怎樣才能循環所有輸入值?

回答

2

你在一個jQuery實例使用each,例如:

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的API有時有點混亂。這是其中的一次。 jQuery有兩個相似但功能不同的函數:您可以調用jQuery實例的each(請參見上文)和jQuery.each,您可以使用它們循環訪問數組,對象和類似數組的對象。

你的代碼使用jQuery.each(jQuery('[name="input-data"]', function...確實有效,因爲jQuery實例是類似數組的,但是在函數中你沒有包裝DOM元素,這就是爲什麼val()不起作用。但是,以上是通過一組匹配元素循環的普通方式。

0

嘗試

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

演示:Fiddle

0
$(document).ready(function(){ 
    $('input').each(function(){ 
    console.log($(this).val()); 
    }); 
    } 
}); 
0

您使用.each()不正確。試試這個:

jQuery('[name="input-data"]').each(function() { 
    // Use $(this) to access current object 
}); 
-1

你正在使用HTML5,不是嗎?你爲什麼不使用給定的HTML5驗證? 只需設置屬性「required ='true'」,你應該完成;-)

也有一個很好的方式來做到這一點在jQuery的移動。如果我記得正確的話,你必須將類'required'設置爲想要的輸入屬性。僅供參考:

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

+0

...因爲當js關閉時,您的功能將失敗。 HTML5表單驗證是本地的,工作正常。 – redflag237 2013-03-15 08:15:42

+1

移動Safari例如不驗證表單。即使桌面版本也沒有這樣做。 – insertusernamehere 2013-03-15 08:17:03

+0

@insertusernamehere:不,只需加載正確的js,它將補償safari缺乏驗證的所有缺點。我做了很多像這樣的項目,而且絕對有可能。 – redflag237 2013-03-15 08:30:29