根据JSON结果生成按钮

时间:2018-12-14 16:21:35

标签: javascript json

我正在尝试根据JSON结果动态创建按钮。生成的按钮数等于JSON信息。但是,对于按钮的名称,我得到了ReferenceError: locationName is not defined。这是生成按钮的正确方法吗?另外(有点偏离主题)如何添加获取相应LocationId的click事件?

<div id="LocationButton"></div>

var locations = [];
function FetchLocations() {
    locations = [];
    $.ajax({
        type: "GET",
        url: "/Locations/GetLocations",
        success: function (data) {
            $.each(data, function (i, x) {
                locations.push({
                    LocationId: x.id,
                    locationName: x.location
                });
            })
            GenerateLocationsButttons(locations);
        },
        error: function (error) {
            alert('Retrieving Locations Failed!');
        }
    })
}

function GenerateLocationsButttons(locations) {
    var more = document.getElementById("LocationButton");
    for (var i = 0; i < locations.length; i++) {
        var btn = document.createElement("button");
        var t = document.createTextNode(locationName);
        btn.appendChild(t);
        more.appendChild(btn);
    }
}

JSON是由ASP.Net MVC 5生成的

public JsonResult GetLocations()
    {
        using (ScheduleCalendarContext_V2 cntx = new ScheduleCalendarContext_V2())
        {
            var events = cntx.Locations.Select(x => new {
                id = x.LocationId,
                location = x.LocationName
            }).ToList();
            return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }

1 个答案:

答案 0 :(得分:0)

您需要从locations数组元素中获取位置名称。

要获取相应的位置ID,您可以将其添加为数据属性。

function GenerateLocationsButttons(locations) {
  var more = $("#LocationButton");
  locations.forEach(({locationName, locationId}) => $("<button>", {
      text: locationName,
      data: {
        location: locationId
      }
    }).appendTo(more);
  });
}

$("#locationButton").on("click", button", function() {
  alert("Button ID " + $(this.data("location"));
});