链接的“组合”无法正常工作

时间:2018-03-30 17:38:10

标签: javascript jquery

小提琴:https://jsfiddle.net/Mrbaseball34/kuj2cz5g/

在代码中,我调用GetYears来填充<ul>数据。当点击一年时,应该将所选年份附加到flyout的文本然后加载品牌<ul> 但是,正在发生的事情是,这些年来它正在“循环”并在点击之后在列表中每年调用yearClick。是的,它会填充品牌<ul>,但会再次开始循环yearClick()

有人可以帮帮忙吗?我猜不到森林里的树木,我想......; - )

var year;
var make;
var model;
var ic;
GetYears();
$("#year-flyout").css("top", $(".m-assisted-decode").position().top);
$("#make-flyout").css("top", $(".m-assisted-decode").position().top  +  40).hide();
$("#model-flyout").css("top", $(".m-assisted-decode").position().top +  75).hide();
$("#parts-flyout").css("top", $(".m-assisted-decode").position().top + 112).hide();

function GetYears() {
    var data = 
[{"year":"2017"},{"year":"2016"},{"year":"2015"},{"year":"2014"},{"year":"2013"},{"year":"2012"},{"year":"2011"},{"year":"2010"},{"year":"2009"}];

    $.each(data, function(i, item) {
        $("#years").append("<li class=\"year\">" + item.year + "</li>");
        $(".year").on("click", yearClick);
    });
    $("#fa_year").hide();
    $("#year-flyout").show();
}
function yearClick(event) {
    year = $(this).text();
    $("#year_value").attr("placeholder", $("#year_value").attr("placeholder") + ":" + year);
    $("#year-flyout").hide();
    // Get the Makes and populate the Makes Flyout
    GetMakes();
}
function GetMakes() {
   var data = 
[{"make":"ACURA"},{"make":"AUDI"},{"make":"BMW"},{"make":"BUICK"},{"make":"CADILLAC"},{"make":"CHEVROLET"},{"make":"CHRYSLER"},{"make":"DODGE"},{"make":"FORD"},{"make":"GMC"},{"make":"HONDA"},{"make":"HUMMER"},{"make":"HYUNDAI"},{"make":"INFINITI"},{"make":"JAGUAR"},{"make":"JEEP"},{"make":"KIA"},{"make":"LAND ROVER"},{"make":"LEXUS"},{"make":"LINCOLN"},{"make":"MAZDA"},{"make":"MERCEDES-BENZ"},{"make":"MERCURY"},{"make":"MINI"},{"make":"NISSAN\/DATSUN"},{"make":"PONTIAC"},{"make":"PORSCHE"},{"make":"RAM"},{"make":"SAAB"},{"make":"SATURN"},{"make":"SCION"},{"make":"SMART"},{"make":"SUBARU"},{"make":"SUZUKI"},{"make":"TOYOTA"},{"make":"VOLKSWAGEN"},{"make":"VOLVO"}];
    $.each(data, function(i, item) {
        $("#makes").append("<li class=\"make\">" + item.make + "</li>");
        $(".make").on("click", makeClick);
    });
    $("#make-flyout").show();
}
function makeClick(event) {
    make = $(this).text();
    $("#make_value").attr("placeholder", $("#make_value").attr("placeholder") + ":" + make);
    $("#make-flyout").hide();
    // Get the Models and populate the Models Flyout
    // GetModels();
}

1 个答案:

答案 0 :(得分:0)

由于您正在使用该类,因此无需在每次添加<li>后附加事件侦听器。只需将其移出每个循环

$.each(data, function(i, item) {
    $("#years").append("<li class=\"year\">" + item.year + "</li>");
});
$(".year").on("click", yearClick);

如果您在Chrome检查器中检查年份元素,则可以在点击时看到所有附加事件,并看到它多次触发同一事件。

enter image description here