我有一些代码不能像我想象的那样工作。我仍然在学习过程中,代码对你们中的某些人来说可能看起来很糟糕。希望你能忽视这一点并帮助我。
我已经构建了一个函数,一旦选中复选框就会将列变为绿色,而未选中复选框则会变为红色。然后我将GREEN值推入一个数组,并在点击&#34时返回它;添加&#34;看起来像这样(<input type="button" id="submit" value="Send data" onclick="sendData(sendMe)">
)我希望它循环并警告值(sendData-function)但没有任何反应。如果我将代码INSIDE放在sendData函数中并将其放在&#34; ChangeBackGroundColor&#34;它有效,但我想使用XHTMLrequest提交它。
function ChangeBackgroundColor(status){
if (status.checked) {
status.parentNode.style.backgroundColor = "green";
sendMe = [];
status.parentNode.previousSibling.style.backgroundColor ="green";
status.parentNode.previousSibling.previousSibling.style.backgroundColor ="green";
status.parentNode.previousSibling.previousSibling.previousSibling.style.backgroundColor ="green";
sendMe.push(status.parentNode.previousSibling.textContent);
sendMe.push(status.parentNode.previousSibling.previousSibling.textContent);
sendMe.push(status.parentNode.previousSibling.previousSibling.previousSibling.textContent);
}
else {
status.parentNode.style.backgroundColor = "red";
status.parentNode.previousSibling.style.backgroundColor ="red";
status.parentNode.previousSibling.previousSibling.style.backgroundColor ="red";
status.parentNode.previousSibling.previousSibling.previousSibling.style.backgroundColor ="red";
sendMe.pop(status.parentNode.previousSibling.textContent);
sendMe.pop(status.parentNode.previousSibling.previousSibling.textContent);
sendMe.pop(status.parentNode.previousSibling.previousSibling.previousSibling.textContent);
}
return sendMe;
}
function sendData(sendMe) {
var arrayLength = sendMe.length;
for (var i = 0; i < arrayLength; i++) {
alert(sendMe[i]);
}
答案 0 :(得分:0)
这是做你想做的事的丑陋方式。使用闭包清理代码会导致太多的问题无法解释为您的问题。
<input type="button" id="submit" value="Send data" onclick="sendData(sendMe)">
<script>
// Create your "sendMe" outside of any particular function.
// This will allow it to be accessed from either function
// with the same variable and not have to be passed.
var sendMe = [];
function ChangeBackgroundColor(status){
var color;
// Reset the array so we don't have the same items on there multiple times.
sendMe = [];
if (status.checked) {
color = "green";
} else {
color = "red";
}
status.parentNode.style.backgroundColor = color;
status.parentNode.previousSibling.style.backgroundColor = color;
status.parentNode.previousSibling.previousSibling.style.backgroundColor = color;
status.parentNode.previousSibling.previousSibling.previousSibling.style.backgroundColor = color;
sendMe.push(status.parentNode.previousSibling.textContent);
sendMe.push(status.parentNode.previousSibling.previousSibling.textContent);
sendMe.push(status.parentNode.previousSibling.previousSibling.previousSibling.textContent);
}
function sendData() {
var arrayLength = sendMe.length;
for (var i = 0; i < arrayLength; i++) {
alert(sendMe[i]);
}
}
</script>