本文最后更新于 115 天前,其中的信息可能已经有所发展或是发生改变。
要求:从输入框中输入一串字符,按回车后输出去重后的字符串
方法一:
<body>
<input type="text" id="input" placeholder="请输入字符串">
<p id="p1"></p>
</body>
<script>
document.onkeydown = function (e) {
var ev = window.event || e;
var code = ev.keyCode || ev.which || ev.charCode;
if (code == 13) {
var str = document.getElementById("input").value
console.log(str)
var str2 = ''
for (var i = 0; i < str.length; i++) {
if (str2.indexOf(str[i]) == -1) {
str2 += str[i]
}
}
console.log(str2)
document.getElementById('p1').innerText = "去重后的字符为:" + str2
}
}
</script>
方法二:
<body>
<input type="text" id="input" placeholder="请输入字符串">
<p id="p1"></p>
</body>
<script>
document.onkeydown = function (e) {
var ev = window.event || e;
var code = ev.keyCode || ev.which || ev.charCode;
if (code == 13) {
var str = document.getElementById("input").value
console.log(str)
var str2 = ''
for (var i = 0; i < str.length; i++) {
if (str2.search(str[i]) == -1)
str2 += str[i];
}
console.log(str2)
document.getElementById('p1').innerText = "去重后的字符为:" + str2
}
}
</script>
运行结果: