我添加认为从输入字段进入列表。添加功能运行良好,但我想检查用户想要添加的字符串是否已存在。所以我想要这样的东西,但不知道使用正确的功能
HTML
First name:
<input type="text" id="firstname">
<br>
<p>Other people's names:</p>
<ul id="demo"></ul>
<input type='button' onclick='changeText2()' value='Submit' />
的javascript
var list = document.getElementById('demo');
function changeText2() {
var firstname = document.getElementById('firstname').value;
var listElement = list.getElementsByTagName("li");
// here is the missing code
if (listElement.text is not in list){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);
}
else alert("is already in !");
}
编辑*
上面的代码jsfiddle。
答案 0 :(得分:2)
你可以创建一个数组并在其中输入每个名称,这是你第一次添加。因此,每次尝试插入新项目时,都会检查数组以查看是否已添加此名称。在代码方面:
var addedNames = [];
var list = document.getElementById('demo');
function changeText2() {
var firstname = document.getElementById('firstname').value;
// Array object has a method called indexOf, with only one argument
// the item we are looking for. If this item is not in the array, the
// method returns -1. Otherwise, the method returns it's position.
// For instance, let that we have defined the following array.
// var numbers = [1,2,3,4].
// Then numbers.indexOf(5) returns -1.
// While numbers.indexOf(4) returns 3.
if (addedNames.indexOf(firstname)==-1){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);
// We add the inserted name in the array for later checks.
addedNames.push(firstname);
}
else alert("is already in !");
}
请查看JSFiddle
答案 1 :(得分:1)
将listElement.text
替换为firstname
。
listElement.text
将返回<li>
,因此listElement.text
将被取消定义。
你可以console.log
检查它
function changeText2() {
var firstname = document.getElementById('firstname').value;
var listElement = list.getElementsByTagName("li");
if (addedNames.indexOf(firstname)==-1){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);
// We add the inserted name in the array for later checks.
addedNames.push(firstname);
console.log(addedNames)
}
else alert("is already in !");
}