jQuery 基础教程(第3版) ---第五章习题答案

 1 //第一题
 2     $('<a href="#top">back to top</a>').insertAfter('div.chapter p:gt(3)');
 3     $('<a id="top"></a>').prependTo('body');
 4     
 5     //第二题
 6     $('.chapter a[href*="top"]').click(function(){
 7         $('<p>You were here</p>').insertAfter(this);
 8     });
 9     
10     //第三题与第四题一起写了 本来是用<strong>标签的,但配合题目,就用<b>标签 
11      $('div#f-author').click(function(){
12         //console.log($(this));
13         if(!$(this).children().is("b"))
14             $(this).wrapInner('<b></b>');
15         else{
16             $(this).text($(this).text());
17         }
18     }); 
19     
20     //或者,这个方法比较差,要用到异常处理
21     $('div#f-author').click(function(){
22         var name =null;
23         try{
24             name = $(this).children().get(0).tagName;}
25         catch(e){
26             name = $(this).get(0).tagName;
27         }
28         if(!(name=="DIV")){
29             $(this).text($(this).text());
30         }else{
31             $(this).wrapInner('<b></b>');
32         }
33     });
34     
35     
36     //第五题
37     $('div.chapter p').each(function(index){
38         var classValue = $(this).attr('class');//取到类值
39         if(classValue){//本身已经定义了类
40             $(this).attr('class',classValue+' '+'inhabitants');
41         }else{//未定义类的,去掉undefine的值
42             $(this).attr('class','inhabitants');
43         }
44     });
45     //第五题实现的功能与下面这条语句是相同的,请特别注意
46     //$('div.chapter p').addClass('inhabitants');
原文地址:https://www.cnblogs.com/wanlxz/p/3452667.html