带有TD和输入的Jquery Map功能

时间:2012-02-29 09:17:38

标签: javascript jquery

我正在尝试将td中的单词和文本框中输入的输入文本组合在一起。

<table width="100%">
<tr>
<td class="CommentWords" width="25%">jsakldjs </td>
  <td class="Label" width="85%"> <input class="Textcomment"
      id="txtCommentWords_3" type="text" width="550px">
</td>
</tr>

<tr class="NormalItem">
    <td class="CommentWords" width="25%">klsajdksajd </td>
    <td class="Label" width="85%"> <input class="Textcomment"
        id="txtCommentWords_4" type="text" width="550px"> </td>
</tr>

</table>

因为我需要选择“commentWords”和“TextComment类”中的所有单词以及相关值。 Fiddler link.

例如:

输出

  

jsakldjsÅInputTextvalue¶//Å将是字段分隔符,¶将是行分隔符

这是我试过的,但截至目前它将返回文本框值或td值。我需要使用字段和行分隔符

来获取所有td值和corrsponding文本值
var list = $(".CommentWords, .Textcomment", this).map(function() {
                            return $(this).val();
                        });

2 个答案:

答案 0 :(得分:2)

您应该执行类似

的操作
var list = $(".CommentWords, .Textcomment", $('#table')).map(function() {
    var $this = $(this);
    if ($this.is('td')) {
        return $this.text();
    } else {
        return $this.val();
    }
});

打印结果

for(i = 0; i < list.length; i++){
    var current  = list[i];
    $('#result').append(current);
    if(i % 2 !== 0){
        $('#result').append(' [end of line] ');
    }else{
         $('#result').append(' [td - input separetor] ');
    }
}

如果你需要连接一个字符串

 var finalString = '';
 for(i = 0; i < list.length; i++){
    var current  = list[i];
    finalString  += current;
    if(i % 2 !== 0){
        finalString += ' [end of line] ';
    }else{
        finalString += ' [td - input separetor] ';
    }
 }

在这里摆弄http://jsfiddle.net/23hgy/2/

答案 1 :(得分:2)

使用<td>函数检索text()的文本。我向你展示了一个小提琴:

http://jsfiddle.net/U9xnj/1/

基本上,你可以做到这一点,但它不是很易读:

var list = $(".CommentWords, .Textcomment").map(function() {
                            return $(this).text() || $(this).val();
                        });