整合3个功能

时间:2012-10-19 15:18:37

标签: jquery

大家好奇,是否有人可以帮我巩固以下代码。我应该能够减少代码行数,但不知道如何实现这一目标。

$(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 个答案:

答案 0 :(得分: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指出的那样,你可以在循环中使用这个函数

答案 1 :(得分: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();
      });
    }
    });

答案 2 :(得分: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();
    });
});

这更具可扩展性。

答案 3 :(得分: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>