0

大家好,想知道是否有人可以帮助我合并以下代码。我应该能够拥有更少的代码行,但不知道如何实现这一点。

$(document).ready(function () {
  $(".question1").hover(function () {
    $(this).append('<div class="tooltip"><p>1This is a tooltip. It is typically used to explain something to a user without taking up space on the page.</p></div>');
  }, function () {
    $("div.tooltip").remove();
  });

  $(".question2").hover(function () {
    $(this).append('<div class="tooltip"><p>2This is a tooltip. It is typically used to explain something to a user without taking up space on the page.</p></div>');
  }, function () {
    $("div.tooltip").remove();
  });

  $(".question3").hover(function () {
    $(this).append('<div class="tooltip"><p>3This is a tooltip. It is typically used to explain something to a user without taking up space on the page.</p></div>');
  }, function () {
    $("div.tooltip").remove();
  });
});
4

4 回答 4

2
function setTooltipMessage ($elem, message) {
    $elem.hover(
        function () {
            $(this).append('<div class="tooltip"><p>'+message+'</p></div>');
        },
        function () {
            $("div.tooltip").remove();
        }
    );
}

然后 :

setTooltipMessage($('.question1'), '1This is a tooltip. It is typically used to explain something to a user without taking up space on the page.');
setTooltipMessage($('.question2'), '2This is a tooltip. It is typically used to explain something to a user without taking up space on the page.');
setTooltipMessage($('.question3'), '3This is a tooltip. It is typically used to explain something to a user without taking up space on the page.');

正如@geedubb 指出的那样,您可以在循环中使用此函数

于 2012-10-19T15:23:56.437 回答
0

我会做这样的事情。

$('.question1, .question2, .question3').hover(function() {
    var question = $(this);
    $('<div/>', {
        'class': 'tooltip',
        'html': '<p>'+ question.data('tooltip') +'</p>'
    }).appendTo(question);
}, function() {
    $(this).find('.tooltip').remove();
});

在您的标记中,您可以像这样指定附加到每个工具提示的内容。

<div class="question1" data-tooltip="1This is a tooltip. It is typically used to explain something to a user without taking up space on the page."></div>
于 2012-10-19T15:32:47.667 回答
0

你可以使用循环吗?

    $(document).ready(function () {
        for(var i = 1; i < 4; i++)
        {
      $(".question" + i).hover(function () {
        $(this).append('<div class="tooltip"><p>' + i + 'This is a tooltip. It is typically used to explain something to a user without taking up space on the page.</p></div>');
      }, function () {
        $("div.tooltip").remove();
      });
    }
    });
于 2012-10-19T15:22:16.767 回答
0
    $(document).ready(function() {
        $('[class^="question"]').hover(function() {
        $(this).append('<div class="tooltip"><p>1This is a tooltip. It is typically used to explain something to a user without taking up space on the page.</p></div>');
    }, function() {
        $('.tooltip').remove();
    });
});

这更具可扩展性。

于 2012-10-19T15:25:26.173 回答