JS- textarea行到javascript数组

时间:2013-10-22 18:16:01

标签: javascript jquery html arrays

我想在js数组中保存textarea行。 这段代码有效,但如果我们在textarea中有空行,则数组元素值在空行后设置为undefined!
演示:http://jsfiddle.net/pYTjR/3/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function check(){
var lines = $('#links').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {

  if (/\S/.test(lines[i])) {
    texts.push($.trim(lines[i]));
    }
var links = texts;
var str = links[i];
alert(i+"-  "+str);
}
}
</script>
</head>
<body>

<textarea id="links" name="upload" cols=80 rows=10>
www.example.com/book111.pdf
www.example.com/book222.pdf
www.example.com/book333.pdf

www.example.com/book444.pdf
www.example.com/book555.pdf
</textarea>

<input type="submit" id="getsize" name="getsize" value="textarea to array" onclick= "check()" />

</body>
</html>

DEMO:http://jsfiddle.net/pYTjR/3/

1 个答案:

答案 0 :(得分:2)

我认为除了没有正确提醒外,它正如您所期望的那样运作。试试这个:

http://jsfiddle.net/pYTjR/7/

function check(){
    var lines = $('#links').val().split(/\n/);
    var texts = [];
    for (var i=0; i < lines.length; i++) {
        if (/\S/.test(lines[i])) {
            texts.push($.trim(lines[i]));
        }
    }
    for (var i=0; i < texts.length; i++) {
        alert(i+"-  "+texts[i]);
    }
}