【发布时间】:2017-08-27 12:02:12
【问题描述】:
我有一系列“.newColor”类的 div。单击其中一个 div 时,其内容将转换为字符串,并使用 push 方法将其添加到名为 myArray 的数组中,前提是它尚未列在数组中。然后,myArray 被转换回一系列具有“.removeItem”类的 div 并显示在水平线上方。
如何单击这些“.removeItem” div,并以与添加方式类似的方式从 myArray 中删除 div 内容(其字符串)?因为它查看 div 内容,将其转换为字符串,如果存在,则从数组中删除该字符串。
var myArray = [];
var myArrayLength;
var newItem = "";
$( ".newColor" ).click(function() {
newItem = $(this).text();
$( '#displayArray' ).html('');
if(myArray.indexOf(newItem) == -1) {
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>
【问题讨论】:
标签: javascript jquery