posts - 431,  comments - 344,  trackbacks - 0

第一章:入门

$()取得页面中的元素

$(document).ready(function(){
 $('.poem-stanza').addClass('emphasized');
});

说明:

$('.poem-stanza')       //取得页面中添加了类poem-stanza的元素
.addClass('emphasized');   //添加Css样式,emphasized为类样式
.removeClass();
 
第二章:选择符

$(document).ready(function(){
 //CSS选择符
 $('#selectedplays>li').addClass('horizontal');          //查找id为selectedplays元素的顶层子元素li,添加样式
 $('#selectedplays>li:not(.horizotal)').addClass('sublevel');    //查找id为selectedplays元素的顶层子元素li,并且没有类horizotal 

 //XPath选择符
 $('a[@href^="mailto:"]').addClass('mailto');           //查找锚元素中属性href以“mailto:”开头的元素
 $('a[@href$=".pdf"]').addClass('pdflink');            //查找锚元素中属性href以“.pdf”结尾的元素
 $('a[@href*="mysite.com"]').addClass('mysite');        //查找锚元素中属性href中包含“mysite.com”的元素(任意位置)

 //自定义选择符
 $('tr:odd').addClass('odd');                   //查找奇数行
 $('tr:even').addClass('even');                  //查找偶数行
 //注::odd()和:even()选择符使用的都是Javascript本身的从0开始得编号方式。表格的第1行编号为0(偶数),而第2行编号为1(奇数)
 $('td:contains("Henry")').addClass('highlight');                   //查找td中包含"Henry"的

 //DOM遍历方法
 $('th').parent().addClass('tableheading');           //查找th的父元素即标题行
 $('tr:not([th]):even').addClass('even');              //查找tr元素中不包含子为th的,并且是偶数行
 $('tr:not([th]):odd').addClass('odd');          
 $('td:contains("Henry")').next().addClass('highlight');         //查找td中包含“Henry”的单元格的下一个单元格
 $('td:contains("Comedy")').siblings().addClass('highlight');  //查找td中包含“Comedy”的同级单元格
 $('td:contains("Comedy")').parent().find('td:gt(0)').addClass('highlight');
 //查找td中包含“Comedy”的父,再去查找td单元格编号大于0的单元格
 $('td:contains("Comedy)').parent().find('td').not(':contains("Comedy")').addClass('highlight');
 //查找td中包含“Comedy”的父,再去查找td单元格不包含“Comedy”的单元格

 //访问DOM元素
 var tag = $('#myelement').get(0).tagName;
});


第三章:事件――扣动扳机

绑定事件:

  .bind(‘click’,function(){})
  $(‘#switcher-large’).bind(‘click’,function(){…});给id为switcher-large的元素绑定click事件

  可简写为
  $(‘#switcher-large’).click(function(){…});

  方法:
  .toggle(function(){},function(){})

接受两个参数(都是函数)第一次点击调用第一个函数,第二次点击调用第二个
$(‘#switcher h3’).toggle(function(){
       $(‘#switcher .button’).addClass(‘hidden’);

},function(){
       $(‘#switcher .button’).removeClass(‘hidden’);

});

.toggleClass()是一种跟优雅得方案,但对于交替执行的操作而言,.toggle()的适用性更强

$(‘#switcher h3’).click(function(){
       $(‘#switcher .button’).toggleClass(‘hidden’); //自动检查该类是否存在
});

  .hover(function(){},function(){})

接受两个函数参数,第一个指针进入,第二个指针离开

$(‘#switcher .button’).hover(function(){
       $(this).addClass(‘hover’);
},function(){
       $(this).removeClass(‘hover’);
});

  .unbind(‘click’)

移除事件
  .trigger(‘click’)

模拟用户操作
$(‘#switcher’).trigger(‘click’); 模拟点击了一次switcher

第四章:效果――为操作添加艺术性

1.修改内联CSS

语法:
.css(‘property’,’value’);
.css(‘property’:’value’,’property’:’value’);

用法:
var currentSize = $(‘div.speech’).css(‘fontSize’);//得到div.speech得字体大小
var num = parasFloat(currentSize,10);  //将currentSize转换为Float型
var unit = currentSize.slice(-2); //返回从指定的字符开始的一个子字符串,-2为倒数第二个
num *= 1.5;
$(‘div.speech’).css(‘fontSize’,num+unit); //设置样式

2.基本的显示和隐藏

.show();
.hide();

用法:
$(‘p:eq(1)’).hide(); //将第二个段落隐藏

3.效果和速度
指定显示速度
3种:slow、normal和fast 时间:0.6、0,4、0.2。也可以指定.show(850)
$(‘p:eq(2)’).show(‘slow’);

淡入和淡出

.fadeIn();        //淡出
.fadeOut();   //淡出

$(‘p:eq(2)’).fadeIn(‘slow’);

4.多重效果

语句:.animate({param1:’value1’,parame2:’value2’},speed,function(){回调});

用法:$(‘p:eq(1)’).animate({height:’show’,width:’show’,opacity:’show’},’slow’);

这里使用简写的show将高度、宽度回复到被隐藏之前的值

5.并发与排队效果
处理一组元素
$(‘div.buttont’).animate({left:650},’slow’).animate({height:38},’slow’);
先移动到left为650的位置,在将高度设置为38
$(‘div.button’)
       .fadeTo(‘slow’,0.5)                            //先淡化
       .animate({left:650},’slow’)           //在移动
       .fadeTo(‘slow’,1.0)                            //在淡出
       .slideUp(‘slow’)                          //最后滑到上方隐藏

注意:排队不适用于其他的非效果方法,例如:.css()
处理多组元素

$(‘p:eq(2)’).slideUp(‘slow’).next().slideDown(‘slow’); 段落3向上滑出,同时段落4向下滑入

回调函数:

Var $thisPara = $(‘p:eq(2)’);
$(‘p:eq(2)’).next().slideDown(‘slow’,function(){

       $thisPara.slideUp(‘slow’);

});

段落4下滑完成后,段落3才开始上滑

第五章:DOM操作-基于命令改变页面

1.操作属性
非css属性

$(document).ready(function(){
    $('div.chapter a[@href*=wikipedia]').each(function(index){
        var $thisLink = $(this);
        $thisLink.attr({
            'rel': 'external',
            'id': 'wikilink-' + index,
            'title': 'learn more about ' + $thisLink.text() + ' at wikipedia'
        });
    });
});

//遍历div.chapter 下面所以锚元素href中包含wikipedia,为其添加属性
深入理解$()工厂函数
$('<a href="#top">back to top</a>');    创建新元素

2.插入新元素

.insertBefore()
.before()

作用相同,区别取决于将它们与其他方法进行连缀

.insertAfter()
.after()

// $('div.chapter p').after('<a href="#top">back to top</a>');

// $('div.chapter p').before('<a href="#top">back to top</a>');

$('<a href="#aaa">back to top</a>').insertAfter('div.chapter p');

$('<a id="aaa" name="top"></a>').prependTo('body');

.perpendTo插入了作为目标的锚

// $('<a href="#top">back to top</a>').insertBefore('div.chapter p');

3.移动元素

$('span.footnote').insertBefore('#footer');
将span中类为footnote的插入到id为footer的前面
标注、编号和链接到上下文
    $('span.footnote').each(function(index){
        $(this)
            .before('<a href="#foot-note-' + (index+1) +
                    '" id="context-' + (index+1) +
                    '" class="context"><sup>' + (index+1) +
                    '</sup></a>');
    });
$('span.footnote').insertBefore('#footer');

遍历span.footnote,在各个元素前加标注后,在将span.footnote添加到#footer前

插入脚注

$('<ol id="notes"></ol>').insertAfter('div.chapter');
$('span.footnote').each(function(index){
        $(this)
            .before('<a href="#foot-note-' + (index+1) +
                    '" id="context-' + (index+1) +
                    '" class="context"><sup>' + (index+1) +
                    '</sup></a>')
            .appendTo('#notes')
            .append('&nbsp;(<a href="#context-'+(index+1)+'">context</a>)');   
});

先创建一个ol元素notes,并添加到div.chapter后面,遍历span.footnote,先添加标注,然后通过appendTo其添加到ol末尾,最后又通过append添加一个锚元素。

4.包装元素

.wrap()
.wrap('<li id="foot-note-' + (index+1) + '"></li>')

5.复制元素

.clone()

$('div.chapter p:eq(0)').clone().insertBefore('div.chapter');

将div.chapter中得第一段复制后插入在div.chapter前面

深度复制

$('div.chapter p:eq(0)').clone(false)

只复制结构,内部的文本没有复制过来,因为文本也是DOM节点

通过复制创建突出引用

var $parentParagraph = $(this).parent('p');

$parentParagraph.css('position','relative');

$(this).clone()

.addClass('pulled')

.prependTo($parentParagraph);

修饰突出引用

$clonedCopy.addClass('pulled')
.find('span.drop')
    .html('&hellip;')
    .end()
    .prependTo($parentParagraph)
    .wrap('<div class="pulled-wrapper"></div>');

var clonedText = $clonedCopy.text();

$clonedCopy.html(clonedText);

第六章:AJAX 让网站与时俱进

1.基于请求加载数据
追加HTML

//载入远程 HTML 文件代码并插入至 DOM 中

$('#dictionary').load('a.html',function(){
      Alert(“加载完毕!”);//回调函数
})

操作JavaScript对象

JSON:
[
{
    "term": "BACKBITE",
    "part": "v.t.",
    "definition": "To speak of a man as you find him when he can't find you."
  },
  {
    "term": "BEARD",
    "part": "n.",
    "definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the head."
  }
]

JQuery:

$.getJSON('b.json',function(data){ //通过 HTTP GET 请求载入 JSON 数据
            $.each(data,function(entryIndex,entry){
                var html = '<div class="entry">';
                html += '<h3 class="term">' + entry['term'] + '</h3>';
                html += '<div class="pare">' + entry['part'] + '</div>';
                html += '<div class="definition">';
                html += entry['definition'];
                if(entry['quote']){
                    html += '<div class="quote">';
                    $.each(entry['quote'],function(lineIndex,line){
                        html += '<div class="quote-line">' + line + '</div>';
                    });
                    if(entry['author']){
                        html += '<div class="quote-author">' + entry['author'] + '</div>';
                    }
                    html += '</div>';
                }
                html += '</div>';
                html += '</div>';
            });

执行脚本

通过 HTTP GET 请求载入并执行一个 JavaScript 文件

$.getScript('c.js',function(){
    Alert(“加载完毕”);//回调函数
});

加载XML文档

//通过远程 HTTP GET 请求载入信息。

$.get('d.xml',function(data){
        $(data).find('entry').each(function(){
                var $entry = $(this);
                var html = '<div class="entry">';
                html += '<h3 class="term">' + $entry.attr('term') + '</h3>';
                html += '<div class="part">' + $entry.attr('part') + '</div>';
                html += '<div class="definition">'
                html += $entry.find('definition').text();
                var $quote = $entry.find('quote');
                if($quote.length){
                    html += '<div class="quote">';
                    $quote.find('line').each(function(){
                        html += '<div class="quote-line">' + $(this).text() + '</div>';                    
                    });
                    if($quote.attr('author')){
                        html += '<div class="quote-author">' + $quote.attr('author') + '</div>';
                    }
                    html += '</div>';
                }
                html += '</div>';
                html += '</div>';
                $('#dictionary').append($(html));
            });
        });

2.选择数据格式

3.向服务器传递数据

4.关注请求

方法:

.ajaxStart()
.ajaxStop()

当AJAX请求开始且尚未进行其他传输时,会触发.ajaxStart()的回调函数,相反,当最后一次活动请求终止时,则会执行通过.ajaxStop()注册的回调函数。

示例:  

//当请求时,显示#loading,结束时,隐藏loading

$(document).ready(function(){
$('#loading').ajaxStart(function(){
     $(this).show();
}).ajaxStop(function(){
     $(this).hide();
});
});

5.Ajax和事件

限制函数绑定的作用域

$(document).ready(function(){
var bindBehaviors = function(scope){
     $('h3',scope).click(function(){
         $(this).toggleClass('highlighted');
     });
}; 

bindBehaviors(this);

//这里的绑定作用域是document

$(document).ready(function(){
     $('#letter-a .button').click(function(){
         $('#dictionary').hide().load('a.html',function(){
             bindBehaviors(this);
//这里的是文档中的所以<h3>元素
             $(this).fadeIn();
         });
     });
});

});

6.安全限制

 

posted on 2009-02-14 20:25 周锐 阅读(500) 评论(0)  编辑  收藏 所属分类: Ajax

只有注册用户登录后才能发表评论。


网站导航: