jquery如何替换dom元素(DOM,jquery,web开发)

时间:2024-05-07 22:59:28 作者 : 石家庄SEO 分类 : web开发
  • TAG :

方法:1、利用replaceWith()方法,该方法用于集合中所有匹配的元素,语法为“元素对象.replaceWith(content,function(index))”;2、利用replaceAll()方法,该方法用于把被选元素替换为新的HTML元素,语法为“元素对象.replaceAll(selector)”。

本教程操作环境:windows10系统、jquery3.4.1版本、Dell G3电脑。

jquery替换dom元素

1、replaceWith() 方法

$(selector).replaceWith(content,function(index))

content 必需。规定要插入的内容(可包含 HTML 标签)。

可能的值:

  • HTML 元素

  • jQuery 对象

  • DOM 元素

function(index) 可选。规定返回替换内容的函数。

index - 返回集合中元素的 index 位置。

$(DOM).replaceWith(newContent) 用于替换集合中所有匹配的元素,并且返回被删除的元素集合:

<!DOCTYPEhtml><html><head><title></title><scriptsrc="jquery.js"></script><scripttype="text/javascript">$('document').ready(function(){$('body>input').click(function(){$('body>ul>li:gt(1)').replaceWith('<li>替换后的元素</li>')})})</script></head><body><inputtype="button"value="替换"><ul><li>第一个</li><li>第二个</li><li>第三个</li><li>第四个</li></ul></body></html>

输出结果:

jquery如何替换dom元素

2、replaceAll() 方法

$(newContent).replaceAll(DOM) 与 $(DOM).replaceWith(newContent) 方法功能一样,只不过是参数位置调换了一下(可以直接在后面赋予样式):

<!DOCTYPEhtml><html><head><title></title><scriptsrc="jquery.js"></script><scripttype="text/javascript">$('document').ready(function(){$('body>input').click(function(){$('<li>替换后的元素</li>').replaceAll('body>ul>li:gt(1)').css('color','orange');})})</script></head><body><inputtype="button"value="替换"><ul><li>第一个</li><li>第二个</li><li>第三个</li><li>第四个</li></ul></body></html>

输出结果:

jquery如何替换dom元素

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:jquery如何替换dom元素的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:怎么用php把秒转为时分秒下一篇:

32 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18