2012-10-01 216 views
3

我想用jquery创建一个css工具提示。我的HTML代码自动将链接标题添加到div标签里

<a class="tooltip" href="#" title="My ttitle">Link1</a> 

应该像悬停

<a class="tooltip" href="#" title="My ttitle"><div class="classic">My title</div>Link1</a> 

如何做到这一点使用jQuery的?

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    //prepend span tag 
    var title = $("this").attr("title"); 
    $(".tooltip").prepend("<div class='classic'>".$(this).attr("title")."</div>"); 

}); 

+0

能请得分享的HTML代码。所以这会更容易回答 – Techie

回答

2

在JavaScript中的串联字符串,你应该使用+代替.;

$(".tooltip").prepend("<div class='classic'>" + $(this).attr("title") + "</div>"); 

另外请注意,你不应该在包装你的代码加上引号this对象和this指的是document对象不是你span元素。

+0

感谢您的帮助。 –

-1

我最后的工作输出为

<html> 
     <title>ToolTips Example</title> 
     <style type="text/css"> 
     .tooltip { 
      border-bottom: 1px dotted #000000; color: #000000; outline: none; 
      text-decoration: none; 
      position: relative; 
     } 
     .tooltip div { 
      margin-left: -999em; 
      position: absolute; 
     } 
     .tooltip:hover div { 
      border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; 
      box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); 
      font-family: Calibri, Tahoma, Geneva, sans-serif; 
      position: absolute; left: 1em; top: 2em; z-index: 99; 
      margin-left: 0; width: 250px; 
     } 
     .tooltip:hover img { 
      border: 0; margin: -10px 0 0 -55px; 
      float: left; position: absolute; 
     } 
     .tooltip:hover em { 
      font-family: Candara, Tahoma, Geneva, sans-serif; font-size: 1.2em; font-weight: bold; 
      display: block; padding: 0.2em 0 0.6em 0; 
     } 
     .classic { padding: 0.8em 1em; } 
     .custom { padding: 0.5em 0.8em 0.8em 2em; } 
     * html a:hover { background: transparent; } 
     .classic {background: #FFFFAA; border: 1px solid #FFAD33; } 
     .critical { background: #FFCCAA; border: 1px solid #FF3334; } 
     .help { background: #9FDAEE; border: 1px solid #2BB0D7; } 
     .info { background: #9FDAEE; border: 1px solid #2BB0D7; } 
     .warning { background: #FFFFAA; border: 1px solid #FFAD33; } 
     </style> 

<!-- jQuery --> 
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
     $(".tooltip").each(function(){ 
      $(this).prepend("<div class='classic'>" + $(this).attr("title") + "</div>"); 
     }); 
    }); 
</script>   
</head> 

<body> 
<a class="tooltip" href="#" title="Hello">Classic</a> 
<br /> 
<a class="tooltip" href="#" title="Second Example">Second Example</a> 
</body></html> 
+0

你不需要发布你的最终结果在这里的答案领域:P – l2aelba

+0

但只显示每个链接的第一个标题。 –