2013-05-20 18 views
4

您好我有一個自動從數據庫填充的引導下拉菜單。我試圖在點擊菜單中的某個項目時發生事件。我試過我試圖在引導下拉菜單上實現一個點擊事件

$("body").on("click", ".ddBtnClick", function(event) { 
    console.log("Is it working? Yes!!"); 
}); 

「.ddBtnClick」是分配給列表中每個項目的類。但沒有發生。 以下是從數據庫填充列表的代碼。

$.getJSON("http://jeremiah.abrahamott.com/DadsCarsObjects.txt", function(data){ 
    $.each(data.aaData, function(i, option){ 
    $("#dropdownfill").append($('<li/>').append($('<a/>').attr("id", option.Year).attr("href", "#").attr("tabindex", "-1").addClass("ddBntClick").text(option.Make))) 
    }); 
}); 

這是下拉菜單的html。

<div class="row" style="margin-left:50px;"> 
      <div class="span3"> 
       <div class="btn-group"> 
        <a class="btn dropdown-toggle" data- toggle="dropdown" href="#">Make 
         <span class="caret"></span> 
        </a> 
        <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" id="dropdownfill"> 

        </ul> 
       </div> 
      </div> 
    </div> 

回答

1

是起訴與您的className。您正在註冊ddBtnClick的委託事件處理程序,但實際的類名是ddBntClick

$("body").on("click", ".ddBtnClick", function(event) { 
    console.log("Is it working? Yes!!"); 
}); 

.addClass("ddBntClick"); 

化建設或改變你的事件委派時的類名。

$(function() 
{ 
    $("body").on("click", ".ddBntClick", function(event) { 
     console.log("Is it working? Yes!!"); 
    }); 
}); 
+1

謝謝,這是問題所在。我切換它,它的工作。 – AdamMasters

+0

非常高興它幫助解決您的問題。 – PSL

0

您是否嘗試在document.ready事件中包裝您的Javascript?

$(function() 
{ 
    $("body").on("click", ".ddBtnClick", function(event) { 
     console.log("Is it working? Yes!!"); 
    }); 
}); 

有關更多信息和示例,請參閱jQuery .ready() documentation

此外,你應該對實際的按鈕單擊事件,並使用.click()代替.on()

$(function() 
{ 
    $(".ddBtnClick").click(function(event) { 
     console.log("Is it working? Yes!!"); 
    }); 
}); 

而且,你有錯字

.addClass("ddBntClick") 

應該是:

.addClass("ddBtnClick")