-3

我需要使用 Javascript(不是 jQuery 或其他 js 框架)访问另一个函数的循环内的变量。

这是我的js:

for (x in drinks) {
    for (y = 0; y < drinks[x].length; y++) {
    // testVarGlobal = drinks[x][y].name; doesn't work
        if (drinks[x][y].type == 'type') {

            txt['type'] = '<span>' + drinks[x][y].name + ' - ' + drinks[x][y].price +'</span>';
            document.getElementById("type").innerHTML += txt['type'];

        } // endif
    } // end for
} // end for in

function foo() {
    // on the next line I need the value from the loop - drinks[x][y].name
    var something = document.getElementById(testVarGlobal);
    return something.value;
}
4

2 回答 2

1

很难用当前的片段来判断。也许你的意思是

for (x in drinks) {
    for (y = 0; y < drinks[x].length; y++) {
        if (drinks[x][y].type == 'type') {
            txt['type'] = '<span>' + foo(drinks[x][y].name) + ' - ' + drinks[x][y].price +'</span>';
            document.getElementById("type").innerHTML += txt['type'];
        } // endif
    } // end for
} // end for in

function foo(drinkName) {
    var something = document.getElementById(drinkName);
    return something.value;
}

更新

我无法从您向我展示的 js 中看到 ID007 可能是什么,但假设它是此处的饮料 ID:

onclick="addToBag('+drinks[x][y].id+'

所以你需要

function getUpdatedQty(id) { 
  var prodQty = document.getElementById(id); 
  return prodQty?prodQty.value:0; // handle an ID that does not exist on page
}

function addToBag(id, name, price, quantity) {
  var quantity = getUpdatedQty(id);

调试使用

function getUpdatedQty(id) { 
  var prodQty = document.getElementById(id); 
  var val = prodQty?prodQty.value:0;
  window.console && console.log(id,prodQty,val);
  return val;
}

并按 F12 查看控制台

如果你有 id:4 并且需要 ID004,你可以使用

function pad(num) {
  return "ID"+("000"+num).slice(-3)
}

  var prodQty = document.getElementById(pad(id)); 
于 2013-08-05T12:33:41.327 回答
1
var testVarGlobal = '';

for (x in drinks) {
    for (y = 0; y < drinks[x].length; y++) {
        testVarGlobal = drinks[x][y].name;
        if (drinks[x][y].type == 'type') {

            txt['type'] = '<span>' + drinks[x][y].name + ' - ' + drinks[x][y].price +'</span>';
            document.getElementById("type").innerHTML += txt['type'];

        } // endif
    } // end for
} // end for in

var somethingValue = foo();

function foo() {
    // on the next line I need the value from the loop - drinks[x][y].name
    var something = document.getElementById(testVarGlobal);
    return something.value;
}
于 2013-08-05T12:36:53.580 回答