2016-09-28 27 views
1

说我有表示用于足球比赛输入以下结构发现通过选择和设定值的后代:jQuery的:通过指数

<form> 
    <div class="match"> 
     <div class="scores"> 
      <input type="text"> 
      <input type="text"> 
     </div> 
    </div> 
    <div class="match"> 
     <div class="scores"> 
      <input type="text"> 
      <input type="text"> 
     </div> 
    </div> 
    <div class="match"> 
     <div class="scores"> 
      <input type="text"> 
      <input type="text"> 
     </div> 
    </div> 
</form> 

我想随机填充每个输入,但每一对必须是不同的。

原来这就是我试图做的:

$('form .match .scores').each(function() { 
    var inputs = $(this).find('input[type=text]'); 

    // generate scores... 
    inputs[0].val(score1); 
    inputs[1].val(score2); 
}); 

我不知道,因为试图填充第一输入控制台报告以下错误,当我所缺少的:

Uncaught TypeError: inputs[0].val is not a function 

我在做什么错?

+0

'输入[0]'返回DOM节点,而不是jQuery的集合。使用'inputs [0] .value = score1;'或'inputs.eq(0).val(score1)' –

回答

1

包装你输入一个jQuery选择像$(inputs[0])或者你可以使用input[0].value,因为input [0]是一个dom元素。

$(function(){ 
 

 
$('form .match .scores').each(function() { 
 
    var inputs = $(this).find('input[type=text]'); 
 
    console.log(inputs); 
 
    
 
    $(inputs[0]).val(score1); 
 
    $(inputs[1]).val(score2); 
 
}); 
 
    
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form> 
 
    <div class="match"> 
 
     <div class="scores"> 
 
      <input type="text"> 
 
      <input type="text"> 
 
     </div> 
 
    </div> 
 
    <div class="match"> 
 
     <div class="scores"> 
 
      <input type="text"> 
 
      <input type="text"> 
 
     </div> 
 
    </div> 
 
    <div class="match"> 
 
     <div class="scores"> 
 
      <input type="text"> 
 
      <input type="text"> 
 
     </div> 
 
    </div> 
 
</form>

0

其实我今天回答一个非常类似的问题: jQuery .each() function accessing other selector via indexes

当调用使用括号一个jQuery数组对象(如inputs[0])你要回一个HTML节点元素,而不是一个jQuery对象。 尝试使用inputs.eq(0)将返回jQuery对象的位置我,那么你可以使用jQuery的val()

更多关于EQ,看到jQuery的文档:https://api.jquery.com/eq/

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.