Плагин jQuery, сохраняйте ссылку на оригинальный элемент

0

Я пишу плагин jQuery, который создает элемент div под элементом body. Мне нужно отслеживать этот элемент внутри этого экземпляра плагина.

$.fn.loadOverlay = function(command) {
  return this.each(function() {
    var container = $(this);

    if (typeof command != 'undefined' && command === 'destroy') {
      // remove the referenced DOM node
      return;
    }

    // somehow I need to keep a reference from the plugin instance to this created DOM node
    var overlay = $('<div>').css({
      width: container.outerWidth(true),
      height: container.height() + 1,
      top: container.position().top - 1,
      left: container.position().left
    }).addClass('overlay');

    // this is now globally appended without any reference to this plugin instance
    $('body').append(overlay);
  });
};

Использование было бы чем-то вроде

$('#someElement').loadOverlay(); // create the overlay
// ...
$('#someElement').loadOverlay('destroy'); // destroy the overlay

Сначала я просто добавил его под выбранный элемент, но это вызвало проблемы со столами.

Одним из решений будет счетчик внутри самого модуля, который динамически добавляет идентификаторы или классы к выбранным и созданным элементам, но я не знаю, как сохранить переменную static внутри плагина jQuery.

Любая помощь приветствуется!

Теги:
dom
jquery-plugins

1 ответ

0
Лучший ответ

Используйте.selector и добавьте его как класс для наложения

$.fn.loadOverlay = function(command) {
    var selector = $(this).selector.replace("#",'').replace('.','').replace(/ /g,'');

Удалить с помощью селектора

if (typeof command != 'undefined' && command === 'destroy') {
      $('.overlay.'+selector).remove() //here
      return;
}

и добавьте селектор как класс в оверлей

var overlay = $('<div>').css({
      width: container.outerWidth(true),
      height: container.height() + 1,
      top: container.position().top - 1,
      left: container.position().left
    }).addClass('overlay ' + selector); //here

Полный код

$.fn.loadOverlay = function(command) {
    var selector = $(this).selector.replace("#",'').replace('.','').replace(/ /g,'');
    alert(selector);
  return this.each(function() {
    var container = $(this);

    if (typeof command != 'undefined' && command === 'destroy') {
      $('.overlay.'+selector).remove()
      return;
    }
    // somehow I need to keep a reference from the plugin instance to this created DOM node
    var overlay = $('<div>').css({
      width: container.outerWidth(true),
      height: container.height() + 1,
      top: container.position().top - 1,
      left: container.position().left
    }).addClass('overlay ' + selector);
    // this is now globally appended without any reference to this plugin instance
    $('body').append(overlay);
  });
};

тогда

$('#someElement').loadOverlay();
$('#sameElement').loadOverlay('destroy'); //removes overlay connected to the selector element
  • 0
    Проблема в том, что могут быть и «анонимные» элементы без идентификаторов.
  • 0
    Как $ ('div'). LoadOverlay ()?
Показать ещё 8 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню