如何使用addEventListener获取元素列表?

时间:2015-09-09 09:26:42

标签: javascript html href addeventlistener

有人可以帮忙吗?我正在进行这个项目...我希望当点击“玩家”数组中的列表项时,他们应该移动到“实际玩家”列表。我想使用一个事件监听器....下面是我的代码......

JAVASCRIPT

 function init(){   
    var players = ["Player1", "Player2", "Player3", "Player4",
                   "Player5"];     
    var listItems = document.getElementById("first"); 
    for (var i = 0; i < players.length; i++){
    var newPlayersList = document.createElement("li"); 
    newPlayersList.ClassName = "list-item";
    var listItemsValue = document.createTextNode(players[i]); 
    newPlayersList.appendChild(listItemsValue);
    listItems.appendChild(newPlayersList);  
    } 

//Below is where i write the codes to set the elements of the 'players' array to move to the 'actual-players' list. But it doesn't work!

    var players = document.getElementsByClassName("list-item");
    for(var i=0; i<players.length; i++){
    players[i].addEventListener("click", function(){
        var text = this.innerHTML;     
        var liElement = document.createElement("li");

        liElement.ClassName = "test";
        var text = document.createTextNode(text);

        liElement.appendChild(text);
           var lis = document.getElementById("actual- 
           players").getElementsByTagName("li");  
            if (lis.length == 4){
                alert("Don't let more than four players");

            } else {
                document.getElementById("actual-
                players").appendChild(liElement);
                this.remove(); 
            }

      });
    } 
  }
 window.onload = function(){
    init();     
};

HTML

<html>    
<head> 
    <title>Table Soccer Teams</title>
    <link rel="stylesheet" type="text/css" href="soccer.css" />
    <script type="text/javascript" src="table_soccer.js" ></script> 
</head> 
<body>    
    <a id="reset" href="javascript:location.reload(true)" 
    class="btn">Reset</a> 

    <div id="soccer_field">
      <div class="players"  onsubmit="return(validateForm ());">
          <h2>Possible Players</h2>
          <ul id="first"></ul>
          <p class="one">Click on names above <br>to select actual
          players</p>
      </div>

      <div class="actual_players">
          <h3>Actual Players</h3>
          <ul id="actual-players" ></ul> 

          <p class="two">Click button below to <br>generate Teams</p>
          <br>
          <a id="generate" href ="#" class="btn">Click here</a>
    </div>      
</div>     
</body>
</html>

0 个答案:

没有答案