jQuery - 设置内容和属性

张开发
2026/4/20 2:43:58 15 分钟阅读
jQuery - 设置内容和属性
jQuery - 设置内容和属性 学习笔记在上一节中我们学习了如何获取内容和属性本节将重点讲解如何设置修改HTML 元素的内容、属性以及表单值。设置操作是动态网页交互的核心。一、设置内容1..html()- 设置 HTML 内容用于替换元素的HTML 内容包括标签。语法$(selector).html(content);$(selector).html(function(index,oldHtml));示例// 1. 直接设置字符串$(#message).html(p stylecolor:red系统消息/p);// 结果p stylecolor:red系统消息/p// 2. 插入 HTML 标签$(#list).html(li项目 1/lili项目 2/lili项目 3/li);// 3. 使用函数动态生成内容// 参数index (索引), oldHtml (旧内容)$(#counter).html(function(i,old){returnspan第 (i1) 次更新/span;});// 4. 清空内容$(#box).html();// 清空内部 HTML注意会完全替换元素内部的所有现有内容。插入的字符串会被浏览器解析为 HTML。如果内容包含用户输入需警惕XSS 攻击。2..text()- 设置纯文本内容用于替换元素的纯文本内容自动转义 HTML 标签。语法$(selector).text(textString);$(selector).text(function(index,oldText));示例// 1. 设置纯文本$(#output).text(b加粗文本/b);// 结果显示文本 b加粗文本/b而不是加粗效果// 2. 拼接文本$(#status).text(function(i,old){returnold - 已更新;});// 3. 批量设置多个元素$(p).text(这是所有段落的统一文本);对比.html()和.text()特性.html().text()解析 HTML是渲染标签否显示为文本安全性低需过滤用户输入高自动转义适用场景富文本、动态布局纯文本显示、用户输入3..val()- 设置表单值用于设置表单元素input,textarea,select的值。语法$(selector).val(value);示例// 1. 设置文本框/文本域$(#username).val(张三);$(#bio).val(这是一个自我介绍...);// 2. 设置单选框/复选框通过 value 匹配// HTML: input typeradio namegender valuemale$(input[namegender]).val([male]);// 选中 value 为 male 的选项// 3. 设置下拉框单选$(#city).val(beijing);// 选中 valuebeijing 的 option// 4. 设置下拉框多选// HTML: select multiple$(#skills).val([java,python,sql]);// 同时选中这三个值// 5. 重置表单设置默认值$(#form).find(input, select, textarea).val();二、设置属性1..attr()- 设置 HTML 属性用于设置元素的HTML 属性如src,href,title,class,id等。语法$(selector).attr(attribute,value);$(selector).attr({attribute:value,...});// 设置多个$(selector).attr(attribute,function(index,attr));示例// 1. 设置单个属性$(img).attr(src,new-image.jpg);$(#link).attr(href,https://example.com);// 2. 设置多个属性对象形式$(#avatar).attr({src:avatar-new.png,alt:用户头像,title:点击查看详情});// 3. 使用函数动态设置// 根据索引设置不同的图片$(img).attr(src,function(i,oldSrc){returnimage-(i1).jpg;});// 4. 切换/添加 Class// 注意通常用 .addClass()/.removeClass()但 attr 也可用$(#box).attr(class,active highlighted);// 替换所有 class// 5. 移除属性设为 undefined 或 null$(#link).attr(target,undefined);// 移除 target 属性2..prop()- 设置 DOM 属性状态用于设置元素的DOM 属性状态主要是布尔属性checked,selected,disabled,readonly。语法$(selector).prop(property,value);$(selector).prop({property:value,...});$(selector).prop(property,function(index,oldVal));示例// 1. 设置复选框/单选框选中状态$(#agree).prop(checked,true);// 选中$(#agree).prop(checked,false);// 取消选中// 2. 设置下拉框选中不推荐推荐用 .val()$(option[value1]).prop(selected,true);// 3. 禁用/启用表单元素$(#submitBtn).prop(disabled,true);// 禁用$(#submitBtn).prop(disabled,false);// 启用// 4. 设置只读$(#readonlyField).prop(readonly,true);// 5. 批量设置状态$(input).prop({disabled:false,readonly:false});// 6. 切换状态取反$(#chk).prop(checked,function(i,oldVal){return!oldVal;// 如果选中则取消未选中则选中});三、.attr()vs.prop()设置区别场景推荐方法示例HTML 初始属性.attr()src,href,id,class,title布尔状态当前.prop()checked,selected,disabled,readonly动态切换状态.prop()$(#chk).prop(checked, true)修改链接/图片源.attr()$(img).attr(src, new.jpg)错误示例// ❌ 不推荐用 attr 设置 checked可能失效$(#chk).attr(checked,true);// 只修改了初始属性不改变当前状态// ✅ 正确用 prop 设置 checked$(#chk).prop(checked,true);// 立即生效四、实际应用案例1. 动态表单填充functionfillForm(userData){$(#username).val(userData.username);$(#email).val(userData.email);$(#bio).text(userData.bio);// 纯文本防 XSS$(#avatar).attr(src,userData.avatarUrl);// 设置单选/复选$(input[namegender][valueuserData.gender]).prop(checked,true);$.each(userData.hobbies,function(i,hobby){$(input[namehobby][valuehobby]).prop(checked,true);});// 设置下拉框$(#city).val(userData.city);}2. 图片切换功能// 点击缩略图切换大图$(.thumb).click(function(){varnewSrc$(this).attr(data-full);$(#mainImage).attr(src,newSrc).attr(alt,$(this).attr(alt)).fadeOut(200).fadeIn(200);// 链式动画});3. 表单验证与提示// 验证失败时设置错误状态functionshowError(input,msg){$(input).addClass(error-border).attr(title,msg)// 设置提示.prop(required,true);// 强制必填}// 验证通过时清除functionclearError(input){$(input).removeClass(error-border).removeAttr(title).prop(required,false);}4. 动态列表内容// 添加新列表项functionaddItem(text){var$li$(li/li);$li.text(text)// 设置纯文本.attr(data-id,Date.now())// 设置自定义属性.prop(draggable,true);// 设置拖拽属性$(#list).append($li);}五、注意事项1. 覆盖 vs 追加.html(),.text(),.val()是覆盖操作会清空原有内容。如需追加需先获取再设置// ❌ 错误直接覆盖$(#box).html(New);// ✅ 正确追加$(#box).html($(#box).html() New);// 或使用 .append() 方法推荐$(#box).append( New);2. 安全性XSS设置用户输入内容时优先使用.text()。必须使用.html()时务必先过滤/转义 HTML 标签。3. 性能优化批量设置属性时使用对象形式.attr({...})比多次调用更高效。链式调用可减少 DOM 查询次数。4. 布尔属性设置checked,disabled等状态时必须使用.prop()否则可能无效。总结方法设置内容设置属性适用场景.html()✅ (HTML)-富文本、动态布局.text()✅ (纯文本)-安全文本显示.val()✅ (表单值)-表单输入、下拉框.attr()-✅ (HTML 属性)src,href,class等.prop()-✅ (DOM 状态)checked,disabled等掌握这些设置方法配合链式调用可以高效地实现动态网页交互

更多文章