[英]insert element in the dom using javascript or jquery
I am using this script to insert three different span
's to the 1st, 2nd and 3rd li
s. 我正在使用此脚本在第1个,第2个和第3个
li
插入三个不同的span
。
$("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? 有没有一种方法可以重构此代码以消除冗余?
If you want to do it to all li tags that are there: 如果要对其中的所有li标签执行此操作:
$("ul li").each(function(i) {
$(this).prepend("<span>" + (i + 1) + "</span>");
});
If there are more than three li tags and you only want it done to the first three: 如果有三个以上的li标签,而您只希望对前三个标签执行此操作:
$("ul li:lt(3)").each(function(i) {
$(this).prepend("<span>" + (i + 1) + "</span>");
});
Working jsFiddle here: http://jsfiddle.net/jfriend00/qhgad/ 在这里工作jsFiddle: http : //jsfiddle.net/jfriend00/qhgad/
Or you can do this like this 或者你可以这样
$("ul li").prepend( function(index, html){
return ("<span>" + (index+1) + "</span>");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.