jQuery获取从嵌套函数触发事件的元素的id

时间:2015-02-23 01:18:49

标签: javascript jquery jquery-ui-tooltip

如何从".item"函数中获取getJSON元素的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);

            });

        }

    });

});

我看过here的解释,但我不确定如何在我的案例中传递事件。

3 个答案:

答案 0 :(得分:0)

我就是这样做的

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"));

            });

        }

    });

});

答案 1 :(得分:0)

尝试使用

  

$(本)

要访问当前元素,您可以使用

访问其ID
  

$(本).attr( '编号')

请参阅 http://jqueryui.com/tooltip/#custom-content

答案 2 :(得分:0)

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);
            });
        }
    });
});
相关问题