如何实现getElementByClassName()

时间:2017-06-06 12:11:40

标签: javascript

我有一个包含列表的应用程序,如下所示:

list

当我点击每个刻度线时,书的名称会被添加到下面的文本框中,我希望用一个十字架替换刻度线,用户可以将其删除。

按照目前的情况,当我点击任何一个刻度时,只有第一个列表项框改为这样的十字:

cross

但是,我希望书中的任何标记都改为十字而不是列表顶部的第一个。

我知道这个问题与需要成为类元素而非ID的项有关,因为使用ID标记将始终选择具有该ID的第一个项目。但是,我不确定如何将它实现到我的代码中,因为我已经尝试用带有类名的div来包装刻度线和交叉框,但仍然会发生同样的事情。

JS代码如下所示:

function saveToList(event) {
    if (event.which == 13 || event.keyCode == 13) { 
    
function saveToFB(bookName) {
  
var user = firebase.auth().currentUser;
var bookList = firebase.database().ref('users/' + uid + '/');
var uid = user.uid;

// This will save data to Firebase
bookList.push({
    book: bookName
    });
};

// This is JS which creates the list from firebase data. Split into 3 lists holding 10 books each
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';

for (var i = 0; i < 10 && i < list.length; i++) {

// Creates the list item by adding the firebase object + genLinks which contains the select, remove and delete icons. 
lis += '<li data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
      };
      
for (var i = 10; i < 20 && i < list.length; i++) {
      
lis2 += '<li data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
      };
      
for (var i = 20; i < 30 && i < list.length; i++) {
      
 lis3 += '<li data-key="' + list[i].key + '">' + list[i].book + genLinks(list[i].key, list[i].book) +'</li>';
      };
      
      // Populates the HTML lists with the JS list items
        document.getElementById('bookList').innerHTML = lis;
        document.getElementById('bookList2').innerHTML = lis2;
        document.getElementById('bookList3').innerHTML = lis3;
    };



// This is the area of the JS concerned with generating the icons found alongside each book name and where I need help 



// The google icons wrapped in divs with class names
function genLinks(key, bkName) {
var links = '';
links += '<a href="javascript:del(\'' + key + '\',\'' + bkName + '\')"><div class="deleteBook"><i id="deleteBook" class="material-icons">delete</i></div></a> ';
links += '<a href="javascript:remove(\'' + key + '\',\'' + bkName + '\')"><div class="removeBook"><i id="removeBook" class="material-icons" onclick="showAdd()" style="display: none">clear</i></div></a> ';
links += '<a href="javascript:select(\'' + key + '\',\'' + bkName + '\')"><div class="selectBook"><i id="selectBook" class="material-icons" onclick="showRemove()">check</i></div></a>';
return links;
};


// onClick event from the selectBook icon which hides the tick and replaces with a cross
function showRemove() {
  document.getElementById('removeBook').style.display = 'block';
  document.getElementById('selectBook').style.display = 'none';
}

// onClick event from the removeBook icon which hides the cross and replaces with a tick
function showAdd() {
  document.getElementById('selectBook').style.display = 'block';
  document.getElementById('removeBook').style.display = 'none';
}
<div id="bookListContainer">
    <ol id="bookList"> </ol>
    
    <ol id="bookList2"> </ol>
    
    <ol id="bookList3"> </ol>
</div>

有人告诉我使用getElementsByClassName()但他们没有解释如何这样做。如果有人有任何建议或可以提供一些帮助,我会非常感激。

提前致谢,

2 个答案:

答案 0 :(得分:2)

您可以使用CSS来控制显示的图标。使用复选框还可以轻松了解所选内容。比它是一个简单的查询和循环来获取被检查的项目。

function buildList() {
   /* Get the checked checkboxes */
   var checkboxes = document.querySelectorAll('[name="books"]:checked');
   /* Build up list of the values by looping over the elements */
   var out = [];    
   for (var i=0; i<checkboxes.length; i++) {
       out.push(checkboxes[i].value);       
   }
   /* Join list together and display it */
   document.getElementById("output").innerHTML = out.join(", ")
}
document.getElementById("booklist").addEventListener("change", buildList);
buildList();
[name="books"] {  /* Hide checkbox */
  display: none
}

[name="books"]+i+i { /* Hide the x when not checked */
  display: none
}

[name="books"]:checked+i {  /* Hide the check when checked */
  display: none
}

[name="books"]:checked+i+i { /* show the x when checked */
  display: inline
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<ul id="booklist">
  <li>
    <label>
      <span>Book 1</span>
      <input type="checkbox" value="book1" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 2</span>
      <input type="checkbox" value="book2" name="books" checked/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 3</span>
      <input type="checkbox" value="book3" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 4</span>
      <input type="checkbox" value="book4" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output"></div>

我们可以稍微修改它以处理多个列表。这次我们可以使用数据属性来说明输出项目的位置。我们使用循环将事件监听器添加到父级。

(function() {
  function buildList(listId) {
    /* Get the checked checkboxes */
    var checkboxes = document.querySelectorAll('#' + listId + ' [name="books"]:checked');
    /* Build up list of the values by looping over the elements */
    var out = [];
    for (var i = 0; i < checkboxes.length; i++) {
      out.push(checkboxes[i].value);
    }
    var outputId = document.getElementById(listId).dataset.output;
    /* Join list together and display it */
    document.getElementById(outputId).innerHTML = out.join(", ")
  }


  var lists = document.querySelectorAll(".book-list");
  for (var i = 0; i < lists.length; i++) {
    (function(list) {
      list.addEventListener("change", function() {
        buildList(list.id)
      });
      buildList(list.id);
    }(lists[i]))
  }
}());
[name="books"] {
  /* Hide checkbox */
  display: none
}

[name="books"]+i+i {
  /* Hide the x when not checked */
  display: none
}

[name="books"]:checked+i {
  /* Hide the check when checked */
  display: none
}

[name="books"]:checked+i+i {
  /* show the x when checked */
  display: inline
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<ul id="booklist1" class="book-list" data-output="output1">
  <li>
    <label>
      <span>Book 1</span>
      <input type="checkbox" value="book1" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 2</span>
      <input type="checkbox" value="book2" name="books" checked/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 3</span>
      <input type="checkbox" value="book3" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 4</span>
      <input type="checkbox" value="book4" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output1"></div>

<ul id="booklist2" class="book-list" data-output="output2">
  <li>
    <label>
      <span>Book 5</span>
      <input type="checkbox" value="book5" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 6</span>
      <input type="checkbox" value="book6" name="books"/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 7</span>
      <input type="checkbox" value="book7" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 8</span>
      <input type="checkbox" value="book8" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output2"></div>

答案 1 :(得分:0)

showremove和showadd函数只能更改一个id,即一个box。如果它应该适用于多个盒子,你应该将selectbook和removebook更改为一个类,并添加一个索引来访问一个类。