使用javascript或jquery在dom中插入元素 [英] insert element in the dom using javascript or jquery

查看:114
本文介绍了使用javascript或jquery在dom中插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个脚本将三个不同的 span 插入到第一,第二和第三个 li

I am using this script to insert three different span's to the 1st, 2nd and 3rd lis.

$("ul li:eq(0)").prepend("<span>1</span>");
$("ul li:eq(1)").prepend("<span>2</span>");
$("ul li:eq(2)").prepend("<span>3</span>");

有没有办法重构这个代码来删除冗余?

Is there a way to refactor this code to remove the redundancy?

推荐答案

如果您想对所有的li标签执行此操作:

If you want to do it to all li tags that are there:

$("ul li").each(function(i) {
    $(this).prepend("<span>" + (i + 1) + "</span>");
});

如果有三个以上的li标签,而您只希望前三个完成:每个(function(i){
$(this))($($)

If there are more than three li tags and you only want it done to the first three:

$("ul li:lt(3)").each(function(i) {
    $(this).prepend("<span>" + (i + 1) + "</span>");
});

在这里工作jsFiddle: http://jsfiddle.net/jfriend00/qhgad/

Working jsFiddle here: http://jsfiddle.net/jfriend00/qhgad/

这篇关于使用javascript或jquery在dom中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆