这个简单的jQuery悬停和替换HTML功能有什么问题

时间:2016-02-20 07:15:17

标签: javascript jquery html hover

var originalContentFirst = $('#first').html();
$('#first').hover(function() {
     $('#first').html('<strong>New HTML</strong>');   
}, function() {
     $('#first').html(originalContentFirst); 
});

var originalContentSecond = $('#second').html();
$('#second').hover(function() {
     $('#second').html('<strong>New HTML</strong>');   
}, function() {
     $('#second').html(originalContentSecond); 
});

var originalContentThird = $('#third').html();
$('#third').hover(function() {
     $('#third').html('<strong>New HTML</strong>');   
}, function() {
     $('#third').html(originalContentThird); 
});

var originalContentFourth = $('#fourth').html();
$('#fourth').hover(function() {
     $('#fourth').html('<strong>New HTML</strong>');   
}, function() {
     $('#fourth').html(originalContentFourth); 
});

这是从本网站的其他地方复制和改编的。如您所见,它的功能非常基本。我有4个div(可怕的ID,我知道),并且在悬停时它应该用新HTML替换它们中的HTML。知道为什么这根本不做任何事情吗?我确定我错过了一些相当基本的东西,但我无法弄清楚它到底是什么?

修改:完整的HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Bio</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script language="Javascript" type="text/javascript" src="script.js"></script>
  </head>
  <body>
    <div id=first>
     <span>About Me</span>
    </div>
    <div id=second>
      <span>Past Jobs</span>
    </div>
    <div id=third>
      <span>Projects</span>
    </div>
    <div id=fourth>
      <span>About</span>
    </div>


  </body>
</html>

1 个答案:

答案 0 :(得分:0)

正如Jaromanda X所说 - 你正在加载脚本上面的html,因此它无需附加任何内容。

$(function() { // this waits until all html loaded

    var originalContentFirst = $('#first').html();
    $('#first').hover(function() {
         $('#first').html('<strong>New HTML</strong>');   
    }, function() {
         $('#first').html(originalContentFirst); 
    });

    var originalContentSecond = $('#second').html();
    $('#second').hover(function() {
         $('#second').html('<strong>New HTML</strong>');   
    }, function() {
         $('#second').html(originalContentSecond); 
    });

    var originalContentThird = $('#third').html();
    $('#third').hover(function() {
         $('#third').html('<strong>New HTML</strong>');   
    }, function() {
         $('#third').html(originalContentThird); 
    });

    var originalContentFourth = $('#fourth').html();
    $('#fourth').hover(function() {
         $('#fourth').html('<strong>New HTML</strong>');   
    }, function() {
         $('#fourth').html(originalContentFourth); 
    });

}); // this closes it