我有一系列带有“.newColor”类的div。当单击其中一个div时,其内容将被转换为字符串,并且只有在数组中尚未列出时才使用push方法将其添加到名为myArray的数组中。然后,将myArray转换回一系列具有“.removeItem”类的div,并在水平线之上显示。从Javascript中删除字符串中的字符串
如何单击这些“.removeItem”div,并将divs内容(其字符串)从myArray中以类似的方式从其中添加?就像在它看divs的内容一样,将它转换成一个字符串并从数组中移除该字符串(如果它存在的话)。
var myArray = [];
var myArrayLength;
var newItem = "";
$(".newColor").click(function() {
newItem = $(this).text();
$('#displayArray').html('');
if(myArray.indexOf(newItem) == -1) {
\t myArray.push(newItem);
myArrayLength = myArray.length;
}
for (var i = 0; i < myArrayLength; i++) {
$('#displayArray').append('<div class="removeItem">' + myArray[i] + '</div>');
}
});
.newColor, .removeItem {
border: 1px solid black;
cursor: pointer;
margin: 2px;
padding: 2px;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current array:
<span id="displayArray"></span>
<hr>
Add to array:
<div class="newColor">blue</div>
<div class="newColor">red</div>
<div class="newColor">green</div>
<div class="newColor">orange</div>
<div class="newColor">purple</div>
<div class="newColor">yellow</div>
<div class="newColor">brown</div>
<div class="newColor">pink</div>