2013-10-12 135 views
1

我有这样的HTML:获取所有元素值与循环

<ul id="div_choices" class="sortable ui-sortable"> 
    <li data-original-title="" title=""> 
    <div class="input-prepend input-append"> 
     <input class="input_choice_text" type="text" placeholder="متن گزینه مورد نظر را وارد کنید"> 
    </div> 
    </li> 
    <li data-original-title="" title=""> 
    <div class="input-prepend input-append"> 
     <input class="input_choice_text" type="text" placeholder="متن گزینه مورد نظر را وارد کنید"> 
    </div> 
    </li> 
</ul> 

而且我想要得到的与jQuery的输入文字。我写了这个代码,但它不工作:

alert($("#div_choices > li:first > input").val()); 

alert($("#div_choices li").first().children("div .input_choice_text").val()) 

确实工作:

$('#div_choices li:first div .input_choice_text').val() 

现在,我想所有的输入值与for循环,我用childreneqnth-child但他们都没有工作,这是为什么?

var node = $("#div_choices"); 
var node2 = $("#div_choices li:first div .input_choice_text"); 
for(var i=1;i<=node.children('li').length;i++) { 
    var text = node2.next().children("div .input_choice_text").val(); 
    alltext += text + "\r\n"; 
} 
+0

您针对'input'元素作为'li'的直接孩子,但他们都没有..有一个'DIV '他们之间.. –

回答

0

使用jQuery EQ方法:

var $ul=$('ul#div_choices'); 
var $li=$ul.children(); 
var len=$li.length; 
while(len){ 
    --len; 
    console.log($li.eq(len).find('input').val()); 
} 

使用jQuery孩子的方法:

while(len){ 
    --len; 
    console.log($($li[len].children[0].children[0]).val()); 
} 

对您有帮助吗?

2

尝试jQuery.each()

$("#div_choices .input_choice_text").each(function() { 
    alltext += this.value + "\r\n"; 
}); 
+0

这段代码只是给我第一个emelent的值 – user2830448

+0

我在编辑它的同时。当前的代码应该工作。一探究竟。 – matewka

2

您可以使用.map()方法:

var arr = $('#div_choices .input_choice_text').map(function(){ 
    return this.value; 
}).get(); 

arr是一个数组,如果你需要一个字符串,你可以在阵列转换为使用.join()方法的字符串:

var str = arr.join("glue"); 

.map()遍历选定的元素,使用for循环,你可以这样做:

var $nodes = $("#div_choices .input_choice_text"), 
    arr = []; 

for(var i = 0; i < $nodes.length; i++) { 
    arr.push($nodes.eq(i).val()); 
} 

// arr.join(','); 
+0

此代码只是给我第一个emelent的价值 – user2830448

0
var node = $("#div_choices"); 
      var alltext = ""; 
      var mynode=$("#div_choices li:first div input"); 

      for(var i=1;i<=node.children('li').length;i++) 
      { 
       var text = mynode.val(); 
       alltext += text + "\r\n"; 

       var parent = mynode.parent().parent(); 
       mynode = parent.next().find('div input'); 
      } 
0
var arr = $('#div_choices').find('.input_choice_text').map(function(){ 
    return this.value; 
}).get().join('\r\n'); 

这将返回一个包含所有输入单元(有input_choice_text类),每个新的链接,我认为你是这个值的字符串。我们可以登录这个

console.log(arr); 

,并可以检查空值:

var arr = $('#div_choices').find('.input_choice_text').map(function(){ 
    if(this.value != '') { 
     return this.value; 
    } 
}).get().join('\r\n');