首页 > 解决方案 > 为什么我的 javascript 代码重复 li?

问题描述

我是 Javascript 初学者(这是我的第一个 javascript 程序),我的迷你应用程序有一些问题......

我正在尝试构建一个页面,让您可以选择今天在您的团队中与您一起工作的人。用户应该能够在名称列表中建立自己的列表。

当用户单击“添加到团队”时,它应该删除相应的<li>并将其添加到下面的选定列表中。

按钮需要从添加到团队更改为删除

如果用户选择添加然后删除然后添加相同的内容,我正在努力更改按钮文本内容<li>......

我一直在尝试很多事情,这是我最后一次尝试:

'script type="text/javascript"';

    var selected = document.querySelector('#selected-list ul');
    var team = document.querySelector('#team-list ul');
    var searchBar = document.forms['search-employees'].querySelector('input');

//add to the selected team
 team.addEventListener("click", function(e){
	if(e.target.className == 'add'){
        
        const li = document.createElement('li');
        const employeename = document.createElement('span');
        const deleteBtn = document.createElement('span');
    
        //add content
        deleteBtn.textContent = 'add';
        employeename.textContent = e.target.parentElement.firstElementChild.textContent;
        
        //add classes
        employeename.classList.add("name");
        deleteBtn.classList.add('delete');
    
        // append to document
        li.appendChild(employeename);
        li.appendChild(deleteBtn);
        selected.appendChild(li);  
        console.log(deleteBtn);
    }
})
	
//delete teammate from selected team
selected.addEventListener('click', function(e){    

    if(e.target.className == 'delete'){
        const li = document.createElement('li');
        const employeename = document.createElement('span');
        const addBtn = document.createElement('span');
    
        //add content
        addBtn.textContent = 'delete';
        employeename.textContent = e.target.parentElement.firstElementChild.textContent;
	
        //add classes
        employeename.classList.add("name");
        addBtn.classList.add('add');
    
        // append to document
        li.appendChild(employeename);
        li.appendChild(addBtn);
        team.appendChild(li);  
        //delete from selected
        console.log(addBtn);
    }				
})
//add a new employee - listen to submit event from form
var addForm = document.forms['add-employee'];

addForm.addEventListener('submit', function(e){
	e.preventDefault(); //prevent default behavior
	const value = addForm.querySelector('input[type="text"]').value;
    console.log(value);
		
	//create elements
	const li = document.createElement('li');
	const employeename = document.createElement('span');
	const deleteBtn = document.createElement('span');
    
	//add content
	deleteBtn.textContent = 'delete';
	employeename.textContent = value;
	
    //add classes
    employeename.classList.add("name");
    deleteBtn.classList.add('delete');
    
	// append to document
	li.appendChild(employeename);
	li.appendChild(deleteBtn);
	selected.appendChild(li);  
    
    //apply style
    
})


//filter names
//grab a reference to the form

searchBar.addEventListener('keyup', function(e){
    //term the user is searching
    const term = e.target.value.toLowerCase();
    //names to compare
    const names = team.getElementsByTagName('li');

    Array.from(names).forEach(function(name){
        const fullname = team.firstElementChild.textContent;
        //check if name exists
        if(fullname.toLowerCase().indexOf(term) != -1){
            name.style.display = 'block';
        } else {
            name.style.display = 'none';
        }
    
    })
                           
})

它给了我以下结果:每次我点击按钮时,它都会给我一个副本(对于未找到队友的输入也是如此)此外,一旦删除,我仍然无法回到“添加到团队”。 ..

我希望你们能启发我,我可能花了太多时间在这上面,但我现在无法找到......

这是它所做的一些说明: 在此处输入图像描述

在选定列表中单击删除后,在 此处输入图像描述

谢谢 HTML:

<?php 
	require_once 'core/init.php';	
	include 'includes/checkedboxes.php';
	include 'includes/headerfront.php';
	//include_once 'includes/dbh.inc.php';
	if(Session::exists('Success')){	
		echo Session::flash('Success');
	}
?>
<html>

<head>
  <link rel="stylesheet" href="styleChief.css">

</head>

<body>
  <section class="team">
    <div id="wrapper">
      <div id="container-left">
        <div id="search">
          <h2 class="title">Who was in your team today?</h1>
            <form id="search-employees">
              <input type="text" name="search" placeholder="Search a name..">
            </form>
        </div>

        <div id="team-list">
          <h3 class="title">Team list</h3>
          <p>Select today's teammates</p>
          <ul>
            <li>
              <span class="name">name</span>
              <span class="add">Add to the team</span>
            </li>
            <li>
              <span class="name">name 1</span>
              <span class="add">Add to the team</span>
            </li>
            <li>
              <span class="name">name 2</span>
              <span class="add">Add to the team</span>
            </li>
            <li>
              <span class="name">name 3</span>
              <span class="add">Add to the team</span>
            </li>
          </ul>
        </div>

        <div id=newmember class="newmember">
          <h4>
            <a class="not-found" href="#"><img class="img" src="img/not-found.png" width="20" height="20" alt="not-found">
            </a>Teammate not found?</h4>
          <form id="add-employee">

            <h3 class="title">Add a new member:</h3>
            <input type="text" placeholder="New teammate name">
            <button>Add</button>

          </form>
        </div>
      </div>

      <div id="container-right">
        <h2>Selected</h2>
        <div id="selected-list">
          <h3 class="title">You have selected the following teammates for today: </h3>
          <ul>

          </ul>
        </div>
      </div>
    </div>
  </section>

  <section class="part">

    <h2>Which part(s) have you been working on today?</h2>
    <input type="checkbox" name="checklist-part" value="Decoratives"><label>Decoratives</label>
    <input type="checkbox" name="checklist-part" value="Windows"><label>Windows</label>
    <input type="checkbox" name="checklist-part" value="Signage Gibela"><label>Signage Gibela</label>
    <input type="checkbox" name="checklist-part" value="Signage Prasa"><label>Signage Prasa</label>
    <input type="checkbox" name="checklist-part" value="Stripes"><label>Stripes</label>
    <input type="checkbox" name="checklist-part" value="Other"><label>Other</label><br/>
    <input type="submit" name="submit" value="Continue" /><br/>

    </form>

  </section>
  <?php
			$sql="SELECT * FROM dttechnames;";
			$result=mysqli_query($conn,$sql);

		?>

    <script src="app/app.js"></script>
    <script src="app/app.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>

</html>

标签: javascriptjqueryhtmldom

解决方案


我试图解决您的代码段的一些问题(例如<form>缺少标签)。基本上,您在脚本部分工作得太辛苦了。如果您想将 a<li>从一个移动<ul>到另一个,那么将它简单地移动.appendChild()到目标是最简单的<ul>。这样做会自动将其从其原始父级中删除<ul>。由于“移动”操作对所有团队成员都是通用<li>的——无论他们是“团队”还是“选定”组的一部分——我们可以为所有成员使用单个“点击”事件监听器。我将它添加到外部#wrapperdiv 中。

以下片段仅涵盖团队成员选择部分(为了清楚起见,我删除了所有其他脚本组件),但它应该展示基本点:

var grps=['#selected','#team'].map(s=>document.querySelector(s+'-list ul')),
    btn=['Add to the team','Remove from the team'];    
[...grps[1].querySelectorAll('.move')].forEach(sp=>sp.textContent=btn[0])

// move members ...
document.querySelector('#wrapper').addEventListener("click", function(e){
  if(e.target.classList.contains('move')){
    var i=btn.indexOf(e.target.textContent); // i=0 (Adding)  or  i=1 (Removing) ?
    e.target.textContent=btn[1-i];           // exchange button caption
    grps[i].appendChild(e.target.parentNode) // move team member ...
  }
})
li {margin: 10px}
.move{
    float: right;
    background: #9361bf;
    padding:4px;
    border-radius: 3px;
}
<section class="team">
    <div id="wrapper">
      <div id="container-left">
        <div id="search">
          <h2 class="title">Who was in your team today?</h1>
            <form id="search-employees">
              <input type="text" name="search" placeholder="Search a name..">
            </form>
        </div>

        <div id="team-list">
          <h3 class="title">Team list</h3>
          <p>Select today's teammates</p>
          <ul>
            <li>
              <span class="name">Roman BARON</span>
              <span class="move"></span>
            </li>
            <li>
              <span class="name">Vincent Houdeville</span>
              <span class="move"></span>
            </li>
            <li>
              <span class="name">Jayson Abrams</span>
              <span class="move"></span>
            </li>
            <li>
              <span class="name">Bafana Hlongwane</span>
              <span class="move"></span>
            </li>
          </ul>
        </div>

        <div id=newmember class="newmember">
          <h4>
            <a class="not-found" href="#"><img class="img" src="img/not-found.png" width="20" height="20" alt="not-found">
            </a>Teammate not found?</h4>
          <form id="add-employee">

            <h3 class="title">Add a new member:</h3>
            <input type="text" placeholder="New teammate name">
            <button>Add</button>

          </form>
        </div>
      </div>

      <div id="container-right">
        <h2>Selected</h2>
        <div id="selected-list">
          <h3 class="title">You have selected the following teammates for today: </h3>
          <ul>

          </ul>
        </div>
      </div>
    </div>
  </section>

  <section class="part">

    <h2>Which part(s) have you been working on today?</h2>
    <form id="parts">
    <label><input type="checkbox" name="checklist-part" value="Decoratives">Decoratives</label>
    <label><input type="checkbox" name="checklist-part" value="Windows">Windows</label>
    <label><input type="checkbox" name="checklist-part" value="Signage Gibela">Signage Gibela</label>
    <label><input type="checkbox" name="checklist-part" value="Signage Prasa">Signage Prasa</label>
    <label><input type="checkbox" name="checklist-part" value="Stripes">Stripes</label>
    <label><input type="checkbox" name="checklist-part" value="Other">Other</label><br/>
    <input type="submit" name="submit" value="Continue" /><br/>

    </form>

  </section>

这似乎是您在 StackOverflow 上发布的第一个问题,所以来晚了:“欢迎来到这里!”

但我想指出,你的问题不必要地冗长和复杂。你应该试着把每个问题的注意力集中在一个点上。这将使其他 Stackoverflow 成员更容易回答,而无需先查看大量代码。

最后一句话:您使用 jQuery 标记了您的问题,但是由于您没有在脚本中使用它,因此我也script src="...jquery..."></script>从代码段中删除了该标记。我永远感谢 John Resig 为我们提供了 jQuery,但在现代浏览器中,您现在几乎可以不用它。


推荐阅读