当前位置:首页 > Web开发 > 正文

jQuery入门教程

2024-03-31 Web开发

一、append()和appendTo() 1.1 append()方法 <body> <p>好好学习</p> <button>append() 方法</button> </body> <script> $(‘button‘).click(function() { $(‘p‘).append(‘<p>天天向上</p>‘); }); </script>

技术图片

1.2 appendTo()方法 <body> <p>好好学习</p> <button>appendTo() 方法</button> </body> <script> $(‘button‘).click(function() { $(‘<p>天天向上</p>‘).appendTo(‘p‘); }); </script>

技术图片

1.3 append()和appendTo()比较

(1)用法相同
在被选元素的结尾(仍然在内部)插入指定内容。

(2)不同之处
内容和选择器的位置不同,以及 append() 能够使用函数来附加内容。

二、html()方法 2.1 返回元素内容 当使用该方法返回一个值时,它会返回第一个匹配元素的内容 (inner HTML)。 <body> <p>好好学习</p> <button>返回被选元素的内容</button> </body> <script> $(‘button‘).click(function() { alert($(‘p‘).html()); }); </script>

技术图片

2.2 设置元素内容

当使用该方法设置一个值时,它会覆盖所有匹配元素的内容 (inner HTML)。

<body> <p>好好学习</p> <button>设置被选元素的内容</button> </body> <script> $(‘button‘).click(function() { $(‘p‘).html(‘天天向上‘); }); </script>

技术图片

2.3 使用函数来设置元素内容

(1)语法

$(selector).html(function(index,oldcontent))

(2)参数

参数 描述
function(index,oldcontent)   规定一个返回被选元素的新内容的函数。index - 可选。接收选择器的 index 位置。oldcontent - 可选。接收选择器的当前内容。  

(3)示例

<body> <p>好好学习</p> <p>天天向上</p> <button>设置被选元素的内容</button> </body> <script> $(‘button‘).click(function() { $(‘p‘).html(function (n) { return ‘这个 p 元素的 index 是‘ + ‘ ‘ + n; }); }); </script>

技术图片

三、append()、appendTo()和html()的区别

(1)append()和appendTo()方法是在被选元素的结尾(仍然在内部)插入内容,是在原有内容的基础上增加

(2)html()方法是覆盖所有内容,是原有的内容被替换

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/42590.html