jQuery element traversal, create, add, delete operations

jQuery element traversal, create, add, delete operations

  1. Element traversal
    Syntax 1: $('div').each(function(index,ele){ })(mainly used to traverse elements)
//html代码
		    <div>1</div>
		    <div>2</div>
		    <div>3</div>
//jQuery代码(记得引入jQuery文件)
            $('div').each(function(index,ele){
                $(ele).css('color','yellow');//把所有的div字体颜色改为yellow
            })

Example: Change the color of each font of the div to the corresponding color in the array arr = ['red','green','blue'], and calculate the sum of the numbers in the div

var arr=['red', 'green', 'blue'];
var sum=0;
$('div).each(function(index,ele){
	$(ele).css('color',arr[index]);
	sum+=parseInt($(ele).text());
})
console.log(sum);//6

Syntax 2: $.each($('div'),function(index,domEle){ })(mainly used to traverse and process data (objects, arrays))

			//遍历数组
			var arr=['red', 'green', 'blue'];
            $.each(arr, function(index, ele) {
                console.log('索引号是' + ':' + index + '    ' + '对应的值是:' + ele);
            });
            //运行结果如下:
            /*索引号是:0    对应的值是:red
			索引号是:1    对应的值是:green
			索引号是:2    对应的值是:blue*/
			//遍历对象
			$.each({name: 'jisoo',age: 25},function(index,ele){
				console.log(index);//返回属性名name,age
				console.log(ele);//返回属性值jisoo,25
			})
  1. Element creation
var newDiv=$('<div>我是新创建的div</div>');
var newUl=$('<ul>我是新创建的ul</ul>');
var newLi=$('<li>我是新创建的li</li>');
  1. Element addition
    The tags added above will not be displayed on the page, because they have not been added to the DOM tree
//内部添加,因为div,ul,li都是body的子元素(使用append方法)
$('body').append(newDiv);
$('body').append(newUl);
$('body').append(newLi);

After adding these newly created tags to the <body>tags, they can be displayed on the page. The running results are as follows:
Insert picture description here

//外部添加,使用after()和before()方法
//html代码
    <ul>
        <li>我是旧的</li>
    </ul>
    <div class="div">我是旧的div</div>
//jQuery代码(记得引入jQuery文件)
    var newDiv=$('<div>我是新的div</div>');//创建新的div标签
    $('.div').after(newDiv); //添加到目标元素的后面
    $('.div').before(newDiv); //添加到目标元素的前面
  1. Element deletion
    ele.remove() deletes the matched element
$(newDiv).remove();//删除新创建的div元素

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110722069