簡體   English   中英

jQuery從嵌套函數中獲取觸發事件的元素的id

[英]jQuery get id of element that triggered event from nested function

如何從getJSON函數內部獲取".item"元素的 id?

jQuery(document).ready(function() {

    $(".item").tooltip({
        items: "div",
        content: function(callback) {

            $.getJSON('mydata.json', function(data) {

                var country = event.target.id;

                console.log(country);

            });

        }

    });

});

我在這里看到了解釋,但我不確定如何在我的情況下傳遞事件。

這就是我要做的

jQuery(document).ready(function() {

    $(".item").tooltip({
        items: "div",
        content: function(callback, this) {
                        var $obj = $(this);
            $.getJSON('mydata.json', function(data, $obj) {

                var country = event.target.id;

                console.log(country);
                console.log($obj.attr("id"));

            });

        }

    });

});

嘗試使用

$(這個)

訪問當前元素,然后您可以通過使用訪問其ID

$(this).attr('id')

http://jqueryui.com/tooltip/#custom-content

在您的內容回調中, this指的是正在調用其工具提示的元素,因此您可以使用this.id來獲取當前元素的id

jQuery(function ($) {
    $(".item").tooltip({
        items: "div",
        content: function (callback) {
            var el = this;
            $.getJSON('mydata.json', function (data) {
                var country = el.id;
                console.log(country);
            });
        }
    });
});

暫無
暫無

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

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