我们说我有#Fred;'的输入。 如何打印它看起来像这样?
Character List:
F
r
e
d
并且全部用id = 'msg2'
到目前为止,我能写的所有内容都是F或d
道歉,忘了包含代码
function start () {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString (pString) {
for (i = 0; i < pString.length; i++) {
t = i + 1
var vReturnName = ('Character list: <br />' + (pString.substring(i, t)))
}
return (vReturnName);
}
答案 0 :(得分:1)
拆分字符串并使用forEach循环遍历数组然后创建新元素并将其放入DOM中:
let str = "FRED";
str.split('').forEach(s => {
let p = document.createElement('p');
p.textContent = s;
document.body.appendChild(p);
})
p{border-bottom:solid 1px #c8c8c8;}
答案 1 :(得分:0)
使用String#split
获取每个角色的array
。
使用Array#join
获取与<br><br>
var name = "Fred";
var newName = name.split('').join('<br><br>');
document.getElementById('msg2').innerHTML = newName;
&#13;
<div id='msg2'></div>
&#13;
答案 2 :(得分:0)
您必须拆分文本并将其附加到div,如下所示:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
$('#msg2').append(characters[i]+'<br/>');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = 'msg2'></div>
&#13;
如果使用Pure JS:
var string = 'Fred';
var characters = string.split('');
for(var i=0; i< characters.length; i++)
{
document.getElementById('msg2').innerHTML+=characters[i]+'<br/>';
}
&#13;
<div id = 'msg2'></div>
&#13;
答案 3 :(得分:0)
您的代码几乎没有问题:
var vReturnName =
将始终具有最后一个值,因为您将覆盖它。在循环外移动声明,并使用vReturnName +=
追加(pString.substring(i, t))
这会为您提供单个字符,但您不会在其后添加<br/>
,因此您将没有换行符。您也可以使用string.charAt
代替它。for (i = 0;
任何没有var|let|const
定义的变量都会变为全局。
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = 'Character list: <br />'
for (i = 0; i < pString.length; i++) {
t = i + 1
vReturnName += (pString.substring(i, t) + "<br/>")
}
return (vReturnName);
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>
function start() {
var vName = document.getElementById('custname').value;
var vLength = processString(vName);
document.getElementById('msg1').innerHTML = vName;
document.getElementById('msg2').innerHTML = vLength;
}
function processString(pString) {
var vReturnName = wrapInP('Character list:')
for (var i = 0; i < pString.length; i++) {
vReturnName += wrapInP(pString.charAt(i))
}
return vReturnName;
}
function wrapInP(str){
return "<p>" + str + "</p>"
}
<input type="text" id="custname" />
<button onclick="start()">Process String</button>
<div id="msg1"></div>
<div id="msg2"></div>