gpt4 book ai didi

javascript - JS-textarea行到javascript数组

转载 作者:行者123 更新时间:2023-12-02 18:13:16 26 4
gpt4 key购买 nike

我想将文本区域行保存在 js 数组中。这段代码可以工作,但是如果我们在文本区域中有空行,则空行后的数组元素值设置为未定义!
演示: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/

最佳答案

我认为它的功能符合您的预期,只是没有正确发出警报。试试这个:

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]);
}
}

关于javascript - JS-textarea行到javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19525354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com