问题描述
我有一个网页正在尝试选择和替换/删除一个值。当我单击选择时,在控制台中显示它正在选择我要选择的项目,但是当在splice命令中输入值时,它只会更改数组的第一个条目。
第一个功能是根据位置选择条形,截面函数是条形数组值,条形和按钮出现的位置,如果值是-1,它将删除该值,否则将替换该值它
function clickBar(Event) {
//Receives position in xy for user clicks
var posX = Event.clientX;
var posY = Event.clientY;
console.log("X = "+posX +" Y = "+ posY);
var barWidth= 500/barVals.length;
console.log("Bar Width = "+barWidth);
var barNum;
//checks to see if click was within the confines of the area that the Boxes are displayed
//if so barNum is calculated to show which position in the array you are clicking on
if(posY >topY && posY < bottomY && posX > leftX && posX < rightX){
console.log("Inside");
barNum = Math.floor((posX - leftX) / barWidth);
console.log("Bar Number = "+barNum);
} else {
console.log("Outside");}
if (barNum > -1) {
replaceBar(barNum)
}
console.log(barVals);
draw();
}
document.addEventListener("click",clickBar);
function replaceBar(barNum) {
console.log("Bar Number2 = "+barNum);
var replaceBox = document.getElementById('replaceVal');
var replaceBtn = document.getElementById('replaceBtn');
var displayBoxSetting = replaceBox.style.display;
var displayBtnSetting = replaceBtn.style.display;
//hiding and displaying the edit text Box and button
if (displayBoxSetting == 'block' && displayBtnSetting=='block') {
replaceBox.style.display = 'none';
replaceBtn.style.display = 'none';
}
else {
replaceBox.style.display = 'block';
replaceBtn.style.display = 'block';
}
//Used to replace the value of the
if(replaceBox.value >0) {
barVals.splice(barNum,1,parseInt(replaceBox.value));
colours.push(document.querySelector('input[name="colour"]:checked').value);
replaceBox.value = 0;
draw(); // redraw
}
else if(replaceBox.value == -1){
barVals.splice(barNum,1);
replaceBox.value = 0;
draw(); // redraw
}
textBoxObj.value = 0;
replaceBox.style.display = 'none';
replaceBtn.style.display = 'none';
draw(); // redraw
}
问题是:
if(replaceBox.value >0) {
barVals.splice(barNum,parseInt(replaceBox.value));
它应该从长度为1的barNum位置开始,并取下替换框的int值,并使用它来拼接值
编辑- 我在替换Screenshot of page之前和2nd Screenshot
之后添加了页面的图像解决方法
看来我是用完全错误的方式开始的,所以这里有一个足够不同的解决方案。将其放置在draw函数中,取自画布本身。
canvas.onclick = function mousePos(Event) {
var rect = canvas.getBoundingClientRect();
var posX = Event.clientX- rect.left;
var posY = Event.clientY - rect.height;
console.log("X = "+posX +" Y = "+ posY);
var barWidth= 500/barVals.length;
console.log("Bar Width = "+barWidth);
var barNum;
barNum = Math.floor((posX-60) / barWidth);
if(barNum>=0 && barNum < barVals.length) {
var position = barNum;
console.log(position);
var amount = prompt("Please enter the new value","734");
//barVals[position] = amount;
if(amount >0) {
barVals.splice(position,1,parseInt(amount));
console.log(amount);
draw(); // redraw
}
else if(amount = -1){
barVals.splice(position,1);
colours.splice(position,1)
draw(); // redraw
}else{
alert("Incorrect value entered");
}
}
}