在jQuery选择器中使用函数参数

时间:2017-07-24 16:16:50

标签: javascript jquery

我有一个名为path的对象:

var path = { "firstFloor": ["roomA1", "roomA6", "roomA5", "roomA2", "roomA3", "roomA4", "roomA10"],
  "secondFloor": ["roomB4", "roomB5", "roomB6"],
  "basementFloor": []}

现在我正常选择数组(path.firstFloor等),但是我需要在一个以键为参数的函数中选择这些对,所以:

function draw(floor) { //later on I will call this function with parameter firstFloor
  $(path.floor).each(function(i, val){ //this is where I need to select.
    var roomIdPath = path.firstFloor[i]
    //console.log(roomIdPath);
    var points = d3.select('#'+roomIdPath).attr('points').split(",");
    var midX = (Number(points[0]) + Number(points[6])) / 2;
    var midY = (Number(points[1]) + Number(points[3])) / 2;
    floorArray.push({"x": midX, "y": midY});
  });
}

不确定我是否清楚,基本上,我只需要在jQuery选择器中使用函数参数。反正有吗?

3 个答案:

答案 0 :(得分:2)

如果要发送功能键,可以使用键访问映射到对象路径中键的值。

目前您使用过path.floor,这是错误的,因为它会在您需要使用path[floor]的路径对象中查找名为floor的键。你可以这样做:

 function draw(floor) { //later on I will call this function with parameter firstFloor
      $(path[floor]).each(function(i, val){ //this is where I need to select.
        var roomIdPath = path[floor][i];
        //console.log(roomIdPath);
        var points = d3.select('#'+roomIdPath).attr('points').split(",");
        var midX = (Number(points[0]) + Number(points[6])) / 2;
        var midY = (Number(points[1]) + Number(points[3])) / 2;
        floorArray.push({"x": midX, "y": midY});
      });
    }

答案 1 :(得分:0)

尝试使用括号表示法console.log(variable),参数将是一个值而不是变量,并且不要忘记偶尔使用SKView.allowsTransparency进行调试

答案 2 :(得分:0)

不确定我的问题是否正确: 您可以迭代元素的键(注意地板可能是原型中具有其他属性的对象):

for(floor in floors){
    //do your thing
}
使用Jquery

或更好:

$.each(floors, function(key, value){
    //do the thing you were doing in the question
    //key is your floor name, value is your array of rooms
});