jQuery对页面元素的批量处理
我在日志里介绍过 和空格的区别。为了避免段落的最后一个单词被孤零零的放在第二行,我们可以用" "来代替最后一个空格。例如:
替代后:<h2>Well done is better that well said</h2><h2>A jouney of a thousands miles stats with a single step</h2><h2>Do first things first, and second thing not at all</h2>
<h2>Well done is better than well said</h2><h2>A jouney of a thousands miles stats with a single step</h2><h2>Do first things first, and second thing not at all</h2>
如果我们不想手动去修改HTML代码,那么我们可以用jQuery来实现。下面分别介绍三种方法:数组法、字符串法、替代法。
1.数组法
先把标题分成一个个单词存入数组,然后再把它们还原的时候,在最后一个单词前加入" "。
$(document).ready(function() {var h2Text = '';$('h2').each(function() { //在jQuery里我们用'each'来获取所有'h2'页面元素var h2Array = $(this).text().split(' '),h2Last = h2Array.pop();//注意使用pop后,h2Array将不含最后一个成员h2Text = h2Array.join(' ') + ' ' + h2Last;$(this).html(h2Text);});});
2.字符串法
这种方法将用到字符串的slice函数和lastIndexOf函数。slice函数可以把一个字符串的特定区间取出,例如:
$str = "abcd efg hi"$part1 = $str.slice(0,3); //把$str的开始4个字符取出,得到:abcd$part2 = $str.slice(10); //把$str从第10个字符开始截取到最后,得到:hi
lastIndexOf(' ')顾名思义就是指最后一个空格的索引位置。有了这两个函数,我们就可以把字符串分成两个部分,第二个部分含有最后一个单词,接着,把第二部分加入" ",然后再把两个部分合并。
3.替代法$(document).ready(function() {var h2all, h2a, h2b;$('h2').each(function() {h2all = $(this).text();h2a = h2all.slice(0, h2all.lastIndexOf(' '));h2b = ' ' + h2all.slice(h2all.lastIndexOf(' ')+1);$(this).html(h2a + h2b);});});
这个方法用到正则表达式,和前两种方法相比,显得要简洁许多。
$(document).ready(function() {var h2Text = '';$('h2 a').each(function() {h2Text = $(this).text().replace(/ (\S+)$/,' $1');//\S代表非空格字符$(this).html(h2Text);});});
标签: Javascript, Jquery



0 条评论:
发表评论
指向此帖子的链接: