Скрыть всплывающую подсказку, если содержимое не найдено

Мне нужно скрыть всплывающую подсказку, если контент не найден. Пытаюсь заставить его работать, но, кажется, безрезультатно. Я использую более старую версию qtip, которая называется jquery.qtip-1.0.0-rc3.js. я пытался использовать

if (!html) {
    $(this).remove();
}

это сработало. Он показывал только изображения всплывающей подсказки с содержимым, но при наведении курсора всплывающее окно не появлялось. Ниже приведен мой полный код всплывающей подсказки. Пожалуйста помогите. Что мне здесь не хватает?

$(document).ready(function () {

    $(".form-field").each(function () {

        var optionLabel = $(this).children('.form-label');
        var optionLabelText = optionLabel.text();


        if ($("img", this).length < 1) {
            $(this).children('.form-label.form-label--alternate.form-label--inlineSmall').append("&nbsp;<div class='help_div' style='float:right;'><img src='/content/help.png'  alt='" + optionLabelText + "'/></div>");
        }

    });


    $('.help_div').each(function () {

        var slug = slugify($("img", this).prop('alt'));
        console.log(slug);
        var html = $("#" + slug).html();
        var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
        titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"
        if (!html) html = "Description not available yet."



        $(this).qtip({
            content: html,
            position: {
                corner: {
                    tooltip: 'topRight',
                    target: 'bottomLeft'
                }
            },
            style: {
                tip: {
                    corner: 'rightTop',
                    color: '#6699CC',
                    size: {
                        x: 15,
                        y: 9
                    }
                },
                background: '#6699CC',
                color: '#FFFFFF',
                border: {
                    color: '#6699CC',
                }
            }
        });

    });

    function slugify(text) {
        text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
        text = text.replace(/-/gi, "_");
        text = text.replace(/^\s+|\s+$/g, "");
        text = text.replace(/\s/gi, "-");
        text = text.toLowerCase();
        return text;
    }

});

person user6345655    schedule 20.09.2018    source источник
comment
Привет! не могли бы вы предоставить URL-адрес, где мы можем увидеть его в действии?   -  person Ignacio Catalina    schedule 20.09.2018
comment
Кроме того, вы имеете в виду . help_div, .form-field или оба случая?   -  person Ignacio Catalina    schedule 20.09.2018
comment
@IgnacioCatalina Привет .. Это ссылка suntec-marketplace.mybigcommerce.com/shop-all/test-product Я имею в виду .help_div   -  person user6345655    schedule 20.09.2018


Ответы (2)


Когда вы добавляете $(this).remove(), вам нужно избегать выполнения qtip. Попробуйте добавить возврат после удаления элемента:

if (!html) {
    $(this).remove();
    return;
}

Это весь пример:

$(document).ready(function() {
  $(".form-field").each(function() {
    var optionLabel = $(this).children('.form-label');
    var optionLabelText = optionLabel.text();

    if($("img", this).length < 1) {
      $(this).children('.form-label.form-label--alternate.form-label--inlineSmall').append("&nbsp;<div class='help_div' style='float:right;'><img src='/content/help.png'  alt='"+optionLabelText+"'/></div>");
    }
  });

  $('.help_div').each(function() {
    var slug = slugify($("img", this).prop('alt'));
    var html = $("#" + slug).html();
    var titleq = $("img", this).prop('alt').replace(/[^-a-zA-Z0-9,&\s]+/ig, '');

    titleq = "<strong style='font-size: 12px'>" + titleq + "</strong><br/>"

    if (!html) {
      $(this).remove();
      return;
    }

    $(this).qtip({
      content: html,
      position: {
        corner: {
          tooltip: 'topRight',
          target: 'bottomLeft'
        }
      },
      style: {
        tip: {
          corner: 'rightTop',
          color: '#6699CC',
          size: {
            x: 15,
            y: 9
          }
        },
        background: '#6699CC',
        color: '#FFFFFF',
        border: {
          color: '#6699CC',
        }
      }
    });
  });

  function slugify(text) {
    text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
    text = text.replace(/-/gi, "_");
    text = text.replace(/^\s+|\s+$/g, "");
    text = text.replace(/\s/gi, "-");
    text = text.toLowerCase();
    return text;
  }
});
person Ignacio Catalina    schedule 20.09.2018
comment
Сделанный. Спасибо :) - person user6345655; 30.09.2018

Это должно работать, но я заметил, что когда я запускаю это в консоли для вашего сайта, оно возвращает Uncaught TypeError: Cannot read property 'jquery' of null

Поскольку вы используете более старую версию плагина qtip, похоже, вы сталкиваетесь с этим:

https://github.com/qTip2/qTip2/issues/275

Вызов удаления для переменной html по сути означает передачу нулевого содержимого в функцию .qtip. Я бы рекомендовал попробовать исправление, предложенное в этой проблеме GitHub, или использовать более новую версию плагина qtip.

person Karen White    schedule 20.09.2018
comment
Когда я обновлял версию, это не сработало. Не было всплывающего окна при наведении. Я тоже пробовал исправить, но безрезультатно :( - person user6345655; 21.09.2018