按钮onclick

时间:2016-04-01 04:30:19

标签: javascript jquery html arrays sorting

功能性:

当用户进入主菜单页面时,图像项目集已按字母顺序排列和显示。然后,用户可以选择不同的类别按钮,按钮A将返回具有相同排序字母顺序的一组图像,而按钮B将返回具有相同排序字母顺序的另一组图像。

我做了什么

我有3组图像源数组:

1。)所有图像来源 2.)ButtonA类别图像源 3.)ButtonB类别图像源

我已从阵列中获取所有图像(所有图像源),并插入特定位置说:<div class="Container"><div id= "list" class="innerScroll"></div></div>。然后按照字母顺序显示图像。

这是您的细读代码。

&#13;
&#13;
var BrandNameArray = ['http://lorempizza.com/380/240',
  'http://dummyimage.com/250/ffffff/000000',
  'http://lorempixel.com/g/400/200/',
  'http://lorempixel.com/g/400/200/sports/'
];

var CategoryA = ['http://lorempizza.com/380/240',
  'http://dummyimage.com/250/ffffff/000000'
];
var CategoryB = [
  'http://lorempixel.com/g/400/200/',
  'http://lorempixel.com/g/400/200/sports/'
];
$(function() {
  //Append array of images to list container in alphabetical Order
  BrandNameArray.forEach(function(cur, index, arr) {
    var img = document.createElement('img');
    img.src = cur;
    docFrag.appendChild(img);
  });
  container.appendChild(docFrag);
});

function CatA() {


  //Append array of images to list container in alphabetical Order
  CategoryA.forEach(function(cur, index, arr) {
    var img = document.createElement('img');
    img.src = cur;
    docFrag.appendChild(img);
  });
  container.appendChild(docFrag);

}

function CatB() {

  CategoryB.forEach(function(cur, index, arr) {
    var img = document.createElement('img');
    img.src = cur;
    docFrag.appendChild(img);
  });
  container.appendChild(docFrag);
}
&#13;
.Container {
  position: absolute;
  top: 300px;
  left: 300px;
  height: 600px;
  width: 1260px;
}
.innerScroll {
  position: relative;
  width: 1250px;
  height: 600px;
  font-size: 25px;
  color: #8d8989 !important;
  overflow-y: scroll;
}
#CatA {
  width: 400px;
  height: 350px;
}
#CatB {
  width: 400px;
  height: 350px;
}
&#13;
<div id="ChooseBrand" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display:none; z-index=3; top:0px; left:0px;">
  <div class="Container">
    <div id="list" class="innerScroll"></div>
  </div>
  <button id="CatA" onclick="CatA()">
  </button>
  <button id="CatB" onclick="CatB()">
  </button>
&#13;
&#13;
&#13;

问题:

当我点击buttonA或buttonB时,相应的图像会被添加到当前的图像列表中。

例如,此时,在菜单页面:

1。)所有图像都被排序和显示。

2。)当我点击按钮A时:来自categoryA数组的图像被添加到菜单图像的顶部列表中。

3.)当我点击按钮B时:来自categoryB数组的图像被添加到菜单图像的ontop列表和显示的categoryA图像上。

因此,所有图像都只是添加到每个显示的列表中。

因此,在这个时间点,存在附加的和重复的图像。想问一下,我怎么能纠正这个问题呢?

谢谢。请帮助。

1 个答案:

答案 0 :(得分:1)

我觉得您在添加之前忘记从容器中删除所有图像。 这样做,它应该工作。请让我知道它是否解决了你的问题

var myNode = document.getElementById("foo");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);

}

您还可以查看此问题Remove all child elements of a DOM node in JavaScript