簡體   English   中英

我正在嘗試在bootstrap下拉菜單上實現click事件

[英]I'm trying to implement a click event on a bootstrap dropdown menu

嗨,我有一個從數據庫自動填充的bootstrap下拉菜單。 當我點擊菜單中的某個項目時,我正試圖讓事件發生。 我試過了

$("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>

問題與您的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!!");
    });
});

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

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

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

此外,你應該登記的實際按鈕的Click事件和使用.click()代替.on()

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

另外,你有一個錯字

.addClass("ddBntClick")

應該:

.addClass("ddBtnClick")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM