0

我想在 js 数组中保存 textarea 行。此代码有效,但如果我们在 textarea 中有空行,则数组元素值在空行后设置为未定义!
演示: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>

演示:http: //jsfiddle.net/pYTjR/3/

4

1 回答 1

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]);
    }
}
于 2013-10-22T18:24:52.993 回答