我正在尝试使用 JS 解析 keyup 上的文本输入字段,以显示所有代词已更改的相同文本。它应该是:我,我,我的并生产: 你,你,你的 她/他,她/他,她的/他的 他们,他们,他们的
它非常适合第一组替换品。在第二组和第三组中,它仅替换数组中的最后一个变量集。 :(
我确信有一种更有效的方法来编写这段代码。我已经使每个部分完全重复,试图解决我的问题,但无法解决。我担心我犯了一个简单的错误。
如果你想尝试一下,这里有一个 fiddle 。 http://jsfiddle.net/8k9b83mo/3/
这是原始的 JS:
function grammar() {
text = ' ' + document.getElementById("first_p").value + ' ';
var array = {
" my ": " your ",
" myself ": " yourself ",
" mine ": " yours ",
" I ": " you ",
" me ": " you ",
" our ": " your "
};
for (var val in array)
text = text.split(val).join(array[val]);
document.getElementById('2_pe').innerHTML = text;
text2 = ' ' + document.getElementById("first_p").value + ' ';
var array2 = {
" my ": " her/his ",
" myself ": " herself/himself ",
" mine ": " hers/his ",
" I ": " s/he ",
" me ": " s/he ",
" our ": " her/his "
};
for (var val2 in array2)
text_3pe1 = text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text_3pe1;
text3 = ' ' + document.getElementById("first_p").value + ' ';
var array3 = {
" my ": " their ",
" myself ": " themself ",
" mine ": " theirs ",
" I ": " they ",
" me ": " they ",
" our ": " their "
};
for (var val3 in array3)
text_3pe2 = text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text_3pe2;
}
非常感谢您的帮助!我正在为这个抓狂。
最佳答案
您不会每次通过 for 循环更新 text2
和 text3
,因此只有最后的更改会保存到 text_3pe1
和 text_3pe2
。将 text_3pe1
替换为 text2
,将 text_3pe2
替换为 text3
,例如 this ,您应该会得到您正在寻找的结果。
关于javascript - 使用 JS .split 并多次连接数组。它只运行最后一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26518847/