为什么我的jQuery的.data()用法不能在这种情况下存储我的对象?

时间:2016-02-12 06:57:54

标签: javascript jquery scope garbage-collection overlay

我正在尝试使用jQuery的.data()方法将覆盖对象存储到目标元素,但是每次运行此代码时,目标元素都不会存储任何覆盖。这是我的代码:

var helper = {  // ...      
overlay: function ($target_element, zIndex) {
        var target_dimension = [$target_element.width(), $target_element.height()];
        var target_offset = $target_element.offset();
        var $screen = $("<div class='overlay'></div>")
                        .css({
                          "width": target_dimension[0],
                          "height": target_dimension[1],
                          "background-color": "#554A4A",
                          "opacity": 0.8,
                          "zIndex": zIndex,
                          "position": "absolute",
                          "top": target_offset.top,
                          "left": target_offset.left
                        });
        $target_element.append($screen);
        $target_element.data('overlayobj', $screen); // Here is where my confusion is.
        return $screen;
      },
// ...
}
$(document).ready(function() {
    helper.overlay($('div#test:last'), 1000);
    $('div#test').data('overlayobj'); // I expected to get back the overlay object, but always got an empty {} here.
});

0 个答案:

没有答案