6

当来自 jquery循环时,我无法this从以下 javascript 对象中删除(特定的“事件”) 。this.each()

天气数据:

{
    "events":{
        "Birthday":{
            "type":"Annual",
            "date":"20120523",
            "weatherType":"clouds",
            "high":"40",
            "low":"30",
            "speed":"15",
            "direction":"0",
            "humidity":"0"
        },
        "Move Out Day":{
            "type":"One Time",
            "date":"20120601",
            "weatherType":"storm",
            "high":"80",
            "low":"76",
            "speed":"15",
            "direction":"56",
            "humidity":"100"
        }
    },
    "dates":{
        "default":{
            "type":"clouds",
            "high":"40",
            "low":"30",
            "speed":"15",
            "direction":"0",
            "humidity":"0"
        },
        "20120521":{
            "type":"clear",
            "high":"60",
            "low":"55",
            "speed":"10",
            "direction":"56",
            "humidity":"25"
        }
    }
}

这是.each()循环的缩小版本:

$.each(weatherData.events, function(i){
    if(this.type == "One Time"){
        delete weatherData.events[this];
    }
})
4

2 回答 2

7

您正在使用一个需要字符串(属性名称)的对象。我相信你想要:

$.each(weatherData.events, function(i){
    if(this.type == "One Time"){
        delete weatherData.events[i];
        // change is here --------^
    }
});

...因为$.each将属性名称(例如,"Move Out Day")作为迭代器函数的第一个参数传递,您将其接受为i. 因此,要从对象中删除该属性,请使用该名称。

无偿的活生生的例子| 资源

于 2012-05-21T07:16:10.823 回答
1

您需要项目的名称,而不是对其的引用。使用回调函数中的参数:

$.each(weatherData.events, function(key, value){
  if(value.type == "One Time"){
    delete weatherData.events[key];
  }
});

参考:http ://api.jquery.com/jQuery.each/

于 2012-05-21T07:18:00.187 回答