jQuery--DOM操作(二)
一、元素的特性、属性
特性 attributes vs 属性 properties
- attributes:值为 string
- properties:值为 string、boolean、number、object
- 如果 attributes 是本来在DOM对象中就存在的,attributes和properties 的值会同步;
- 如果 attributes 是本来在DOM对象中就存在的,但是类型为Boolean,那么attributes和properties 的值不会同步;
- 如果 attributes 不是DOM对象内建的属性,attributes和properties 的值不会同步;
代码示例:
<body>
<img id="logo" src="../logo1.jpg" alt="jQuery logo" class="img-jquery" title="jQuery logo" />
<input type="checkbox" id="check"
tabindex="1" style="width:50px; height: 50px;"
title="Check this!" description="just a checkbox" />
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function () {
var checkbox = document.getElementById('check');
// console.log(checkbox.getAttribute('tabIndex'));
// console.log(checkbox.tabIndex);
// console.log(typeof checkbox.getAttribute('tabIndex'));
// console.log(typeof checkbox.tabIndex);
// console.log(checkbox.getAttribute('style'));
// console.log(checkbox.style);
// console.log(typeof checkbox.getAttribute('style'));
// console.log(typeof checkbox.style);
//
// console.log(checkbox.attributes);
console.log(checkbox.getAttribute('title') === checkbox.title);
checkbox.title = 'New title!';
console.log(checkbox.getAttribute('title') === checkbox.title);
checkbox.setAttribute('title', 'Another title!');
console.log(checkbox.getAttribute('title') === checkbox.title);
console.log(checkbox.getAttribute('checked'));
console.log(checkbox.checked);
checkbox.checked = true;
console.log(checkbox.getAttribute('checked'));
console.log(checkbox.checked);
console.log(checkbox.getAttribute('description'));
console.log(checkbox.description);
checkbox.description = '123';
console.log(checkbox.getAttribute('description'));
console.log(checkbox.description);
checkbox.name = 'check';
console.log(checkbox.getAttribute('name'));
console.log(checkbox.name);
checkbox.setAttribute('name', 'Another name!');
console.log(checkbox.getAttribute('name'));
console.log(checkbox.name);
checkbox.style = "width:150px; height: 150px;";
console.log(checkbox.getAttribute('style'));
console.log(checkbox.style);
checkbox.style = {
width: 200,
height: 200
};
console.log(checkbox.getAttribute('style'));
console.log(checkbox.style);
var img = document.getElementById('logo');
console.log(img.attributes);
img.src = '../logo.jpg';
console.log(img.src); //http://localhost:63342/code/logo.jpg
console.log(img.getAttribute('src'));//../logo.jpg
console.log(img.class);//undefined class是js的保留字
console.log(img.getAttribute('class'));//img-jquery
console.log(img.className);//img-jquery 所以对于class,获取属性时使用className,获取特性直接使用class
});
</script>
</body>
二、使用jQuery操作元素的属性、特性和数据
1.操作元素的特性
• 获取特性的值:attr(name):获取第一个元素的值
• 设置特性的值:attr(name, value) attr(attributes)
• 删除特性:removeAttr(name)
代码示例:
<body>
<img id="logo" src="../logo1.jpg" alt="jQuery logo" title="jQuery logo" />
<img id="logo2" src="../logo1.jpg" alt="jQuery logo" class="img-jquery2" title="jQuery logo" />
<input type="checkbox" id="check" tabindex="1" style="width:50px; height: 50px;" title="Check this!" description="just a checkbox" />
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var img = $('img');
var checkbox = $('#check');
// console.log(img.attr('id'));
// console.log(img.attr('class'));
//
// console.log(checkbox.attr('tabIndex'));
// console.log(checkbox.attr('TABINDEX'));
// console.log(checkbox.attr('checked'));
console.log(img.attr('title', 'new title'));
console.log(img.attr({
title: 'new title2',
alt: 'new alt2'
}));
console.log(checkbox.attr({
tabIndex: 2
}));
console.log(img.attr('title', function(index, previousValue) {
return previousValue + '-' + index;
}));
console.log(checkbox.attr({
tabIndex: function(index, previousValue) {
return ++previousValue;
}
}));
console.log(img.removeAttr('title alt'));
console.log(document.getElementById('logo').title);
});
</script>
</body>
2.操作元素的属性
• 获取属性的值:prop(name)
• 设置属性的值:prop(name, value) prop(properties)
• 删除属性:removeProp(name)
代码示例:
<body>
<img id="logo" src="../logo1.jpg" alt="jQuery logo" class="img-jquery" title="jQuery logo" />
<img id="logo2" src="../logo1.jpg" alt="jQuery logo" class="img-jquery2" title="jQuery logo" />
<input type="checkbox" id="check" tabIndex="1" style="width:50px; height: 50px;" title="Check this!" description="just a checkbox" />
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var img = $('img');
var checkbox = $('#check'); //checkbox是一个jQuery对象
console.log(checkbox.prop('checked')); //false
console.log(checkbox.checked);//undefined
//转换为DOM对象就可以获取到了
console.log(checkbox.get(0).checked);//false
console.log(checkbox.attr('checked')); //undefined
console.log(checkbox.get(0).tabindex);//undefined dom里面使用全小写,必须使用驼峰形式
console.log(checkbox.get(0).tabIndex);//1
console.log(checkbox.prop('tabindex')); //1
console.log(checkbox.prop('tabIndex'));//属性区分大小写 ,特性不区分
console.log(checkbox.prop('TABINDEX'));
console.log(img.prop('className'));//img-jquery
console.log(img.prop('class'));//img-jquery
console.log(checkbox.prop('checked', true));//html结构没有改变,只是属性改变了
console.log(checkbox.prop('checked'));
console.log(checkbox.attr('checked', true));
console.log(checkbox.attr('checked'));//undefined
console.log(checkbox.prop('checked'));
console.log(checkbox.attr('checked', false));
console.log(checkbox.prop('checked'));
console.log(checkbox.removeProp('checked'));
console.log(checkbox.prop('checked'));
// console.log(checkbox.prop('checked', true));
// console.log(checkbox.prop('checked'));
// console.log(img.removeProp('title'));
// console.log(img.attr('title'));
// console.log(img.prop('title'));
// console.log(img.removeProp('alt'));
// console.log(img.attr('alt'));
// console.log(img.prop('alt'));
});
</script>
</body>
3.在元素中存取数据
• 获取数据的值:data([name])
• 设置数据的值:data(name, value) data(object)
• 删除数据:removeData([name])
• 判断是否有数据:jQuery.hasData(element)
<body>
<img id="logo" src="../logo1.jpg" alt="jQuery logo" class="img-jquery" title="jQuery logo" data-id="1" data-data1="html data1" />
<img id="logo2" src="../logo1.jpg" alt="jQuery logo" class="img-jquery2" title="jQuery logo" data-foo-42="bar" />
<input type="checkbox" id="check" tabIndex="1" style="width:50px; height: 50px;" title="Check this!" description="just a checkbox" />
<script src="../../../vendor/jquery-1.12.4.js"></script>
<!--<script src="../../../vendor/jquery-3.1.0.js"></script>-->
<script>
$(function() {
var img = $('img');
var checkbox = $('#check');
// img.data('description', 'jquery logo');
// console.log(img.data('description'));
//
// img.data('lastDescription', 'old description');
// console.log(img.data('lastDescription'));
// console.log(img.data('last-description'));
// console.log(img.data('last-Description'));
//
// console.log(img.data('LastDescription'));
// console.log(img.data('Last-Description'));
//
//
// img.data('dataObject', {
// foo: 'bar'
// });
// img.data('dataArray', [1, 2, 3]);
// img.data('dataBoolean', false);
//
// console.log(img.data('dataObject'));
// console.log(img.data('dataArray'));
// console.log(img.data('dataBoolean'));
//
// img.data('dataUndefined', undefined);
// console.log(img.data('dataUndefined'));
//
// img.data({
// data1: 'data1',
// data2: 'data2',
// data3: 'data3'
// });
//
// console.log(img.data());
// console.log(img.eq(0).data());
// console.log(img.eq(1).data());
//
// console.log(img.data('data1'));
// console.log(img.attr('data-data1'));
//
// img.attr('data-data1', '123')
//
// console.log(img.data('data1'));
// console.log(img.attr('data-data1'));
//
// img.data('data1', '456')
//
// console.log(img.data('data1'));
// console.log(img.attr('data-data1'));
console.log($('#logo2').data());
console.log($('#logo2').data('foo-42'));
// $('#logo').data('test', 'test')
// console.log($('#logo').data());
//
// $('#logo').removeData(['test'])
// console.log($('#logo').data());
//
// $('#logo').removeData(['data1'])
// console.log($('#logo').data());
// console.log($('#logo').attr('data-data1'));
$('#logo').data('test', 'test');
$('#logo').removeData();
console.log($('#logo').data());
console.log($.hasData(document.getElementById('logo')));
console.log($.hasData(document.getElementById('check')));
});
</script>
</body>
三、在页面中操作 DOM 元素
1.修改元素样式
①添加或修改 class
• addClass(names)
• removeClass(names)
• toggleClass([names][, switch])
• hasClass(name)
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
.box {
width: 100px;
height: 100px;
}
.red {
background-color: red;
}
.b10 {
border: 10px solid #000;
}
.m10 {
margin: 10px;
}
.p10 {
padding: 10px;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div class="box" id="demo">div</div>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var element = $('#demo');
// element.addClass('red');
// element.addClass('b10 m10 p10');
// element.removeClass('b10 m10 p10');
// element.addClass(function (index, className) {
// console.log(index); //0
// console.log(className);//box
// return 'red';
// });
// element.removeClass(function (index, className) {
// console.log(index);
// console.log(className);
// return 'red';
// });
// if (element.hasClass('hide')) {
// element.removeClass('hide');
// } else {
// element.addClass('hide');
// }
element.toggleClass('hide'); //切换
$('li').each(function(index) {
$(this).toggleClass('red', index % 3 === 0);
});
element.toggleClass('hide box red');
});
</script>
</body>
</html>
②获取或设置 style
• css(name, value)
• css(properties)
• css(name)
③获取或设置元素尺寸
• width(value):只针对该对象集合里的第一个元素,而不是所有元素
• height(value)
• innerHeight(value):包含内边距,不包含边框和外边距
• innerWidth(value)
• outerHeight ([includeMargin]):包含内边距和边框,不一定包含外边距,想要包含外边距,传入布尔参数,true则包含,false则不包含
• outerHeight(value)
• outerWidth ([includeMargin])
• outerWidth(value)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
body {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="box" id="demo">div</div>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var element = $('#demo');
element.css('width', 200);
element.css({
'background-color': 'red', //如果使用-形式,不是驼峰形式,需要用引号括起来
height: 200, //使用px作为默认的
border: '10px solid #000',
marginTop: 100,
mArGinLeft: 100,
width: '+=200'
});
//通过函数设置height index:索引值,value:当前height的值
element.css('height', function(index, value) {
console.log(value); //200px
return parseInt(value, 10) + 50; //带有单位,所以要进行转换
});
console.log(element.css('height')); //获取样式的值;250px
console.log(element.css(['height', 'width', 'border'])); //Object border:"" height:"" width:""
console.log(element.width());
console.log(element.height());
element.css({
width: '50%',
height: '30em'
});
console.log(element.width());//获取到的值是不带单位的 150
console.log(element.height());//250 如果是百分比或其他的单位,会自动转换为相应的像素
element.css({
width: 100,
height: 100,
border: '10px solid #000',
margin: 20,
padding: 30
});
// console.log(element.width());
// console.log(element.height());
// console.log(element.innerWidth());
// console.log(element.innerHeight());
// console.log(element.outerWidth());
// console.log(element.outerHeight());
// console.log(element.outerWidth(true));
// console.log(element.outerHeight(true));
console.log(element.offset());
// element.css({
// position: 'absolute',
// width: 100,
// height: 100,
// border: '10px solid #000',
// margin: 20,
// padding: 30,
// left: 200,
// top: 100
// });
// console.log(element.offset());
//
// element.offset({
// top: 50,
// left: 100
// })
// console.log(element.offset());
console.log(element.position());
});
</script>
</body>
</html>
④获取或设置位置和滚动
• offset(coordinates):返回对象集合第一个元素
• position()
• scrollLeft(value)
• scrollTop(value)
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
body {
margin: 0;
padding: 0;
}
.box {
position: relative;
width: 100px;
height: 100px;
background-color: #cccccc;
}
.item {
position: relative;
width: 50px;
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<div class="box" id="demo">
<div class="item"></div>
</div>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var demo = $('#demo');
var element = $('.item');
console.log(element.offset());//top:20 left:20 相对于文档
console.log(element.position());//相对于父元素
demo.css({
left: 10,
top: 20
});
element.css({
left: 10,
top: 20
});
console.log(element.offset());
console.log(element.position());
demo.css({
overflow: 'hidden'
});
element.css({
margin: 20
});
console.log(element.offset());
console.log(element.position());
});
</script>
</body>
</html>
scroll:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
body {
margin: 0;
padding: 0;
}
.box {
width: 300px;
height: 300px;
border: 1px solid #ccc;
overflow: auto;
}
p {
width: 500px;
}
</style>
</head>
<body>
<div class="box" id="demo">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam asperiores aspernatur at aut harum iure molestias nisi quos vel. A, dicta inventore nisi nobis praesentium quas ullam vero! Beatae enim laborum nam nulla quaerat quos rem. A alias asperiores assumenda rem similique sit suscipit tempora temporibus unde vel voluptatum. A accusamus amet animi cumque delectus ducimus eius, eligendi harum illum inventore ipsum iusto laudantium libero magnam nemo nisi nobis nostrum, obcaecati perferendis placeat possimus provident quo rerum sit sunt suscipit vel veniam. A asperiores at blanditiis, cumque debitis ea eveniet inventore ipsum iure iusto maxime minus mollitia nostrum, pariatur porro quae quas quasi quibusdam sed sequi sit ullam unde ut voluptatibus voluptatum? Ad alias aliquid amet architecto asperiores atque deserunt ducimus est excepturi ipsa laboriosam nemo nesciunt, nobis nulla officiis quibusdam quidem recusandae repellat, sequi sint, suscipit vero vitae? A aliquam dolore ea enim fugiat impedit laudantium minus molestias dolore doloremque eaque fugit id iste maiores, nemo nisi porro quas quibusdam quod tempora, vel velit, veniam! Inventore, omnis?</p>
</div>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var demo = $('#demo');
console.log(demo.scrollTop());
console.log(demo.scrollLeft());
demo.scrollTop(300);
demo.scrollLeft(100);
console.log(demo.scrollTop());
console.log(demo.scrollLeft());
});
</script>
</body>
</html>
2.修改元素内容
①获取或设置元素内容
• html()
• html(content)
• text()
• text(content)
代码示例:
<body>
<ul>
<li class="item1">item-1</li>
<li class="item2">item-2</li>
<li class="item3">item-3</li>
<li class="item4">item-4</li>
<li class="item5">item-5</li>
<li class="item6">item-6</li>
<li class="item7">item-7</li>
<li class="item8">item-8</li>
<li class="item9">item-9</li>
</ul>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var elements = $('li');
console.log(elements.html());//item 只对html第一个元素起作用
console.log(elements.text());//item-1item-2item-3item-4item-5item-6item-7item-8item-9 对jQuery对象集合里的所有元素都起作用
console.log(elements.html('<strong>123</strong>'));
//console.log(elements.text('<strong>123</strong>'));
console.log(elements.html('<script>alert("123")<\/script>'));//包含script时需要转义
});
</script>
</body>
②移动或插入元素
• append(content[, content, ..., content])
• prepend(content[, content, ..., content])
• before(content[, content, ..., content])
• after(content[, content, ..., content])
• appendTo(target)
• prependTo(target)
• insertBefore(target)
• insertAfter(target)
代码示例:
<body>
<h2>title</h2>
<ul>
<li class="item1">新闻标题-1</li>
<li class="item2">新闻标题-2</li>
<li class="item3">新闻标题-3</li>
<li class="item4">新闻标题-4</li>
<li class="item5">新闻标题-5</li>
<li class="item6">新闻标题-6</li>
<li class="item7">新闻标题-7</li>
<li class="item8">新闻标题-8</li>
<li class="item9">新闻标题-9</li>
</ul>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
// var elements = $('li');
//
// elements.append(' <a href="#">阅读更多</a>')
var element = $('ul');
// element.append('<li>append</li>')
// element.prepend('<li>prepend</li>')
// element.after('<li>after</li>')
// element.before('<li>before</li>')
// element.append($('h2')) //移动到元素的最后
// element.append($('.item1'))
// element.append('<p>p1</p>', ['<p>p2</p>', $('h2')], $('.item1'))
//element.append($('h2'))
$('h2').appendTo(element);//等价的
});
</script>
</body>
③包裹元素
• wrap(wrapper)
• wrapAll(wrapper)
• wrapInner(wrapper)
• unwrap():移除元素的父元素
代码示例:
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, veritatis.</p>
<div class="item"></div>
<a href="#">link1</a>
<a href="#">link2</a>
<a href="#">link3</a>
<a href="#">link4</a>
<a href="#">link5</a>
<a href="#">link6</a>
<a href="#">link7</a>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var element = $('p');
element.wrap('<div class="box"></div>');
// element.wrap($('.item'))
// $('a').wrap('<p></p>');
// $('a').wrapAll('<p></p>');
//
// element.wrapInner('<div class="box"></div>');
// $('a').wrapInner('<p></p>');
element.unwrap();
});
</script>
</body>
④移除元素
• remove([selector]):绑定的数据和事件都会被移除
• detach([selector]):移除后还会保留事件和数据
• empty():可以保留元素本身,清除干净元素内容
代码示例:
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
p {
font-size: 12px;
}
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, veritatis.</p>
<div class="item"></div>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var element = $('p');
// element.on('click', function () {
// $(this).css('fontSize', '+=5')
// }).data('data', 'demo')
//
// element.detach()
//
// console.log(element);
//
// element.appendTo($('.item'))
//
// console.log(element.data());
element.empty();
});
</script>
</body>
⑤复制和替换元素
• clone([Even[,deepEven]])
• replaceWith(content)
• replaceAll(target)
代码示例:
<body>
<h2>title</h2>
<div class="item">
<p>Lorem ipsum dolor sit amet.</p>
</div>
<ul>
<li class="item1">新闻标题-1</li>
<li class="item2">新闻标题-2</li>
<li class="item3">新闻标题-3</li>
<li class="item4">新闻标题-4</li>
<li class="item5">新闻标题-5</li>
<li class="item6">新闻标题-6</li>
<li class="item7">新闻标题-7</li>
<li class="item8">新闻标题-8</li>
<li class="item9">新闻标题-9</li>
</ul>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function() {
var element = $('ul');
// $('h2').clone().appendTo(element)
// $('.item').data('item', 'item')
// $('p').data('p', 'p')
//
// $('.item').clone(true, true).appendTo(element)
//
// console.log($('ul .item').data())
// console.log($('ul p').data())
$('h2').replaceWith('<p>hello</p>');
$('<p>hello</p>').replaceAll($('li'));
});
</script>
</body>
注意:
appendTo(target)
prependTo(target)
insertBefore(target)
insertAfter(target)
replaceAll(target)
都是执行了破坏性操作,在链式语法中使用他们的时候,如果要选择先前选择的元素,需要使用end()
⑥处理表单元素值
• val():设置值
• val(value):获取值
代码示例:
<body>
<form>
<p><input type="text" name="text"></p>
<p>
<input type="radio" name="radio" value="1"> radio1
<input type="radio" name="radio" value="2"> radio2
</p>
<p>
<input type="checkbox" name="checkbox" value="1"> checkbox1
<input type="checkbox" name="checkbox" value="2"> checkbox2
</p>
<p>
<select name="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</p>
<p>
<select name="multiSelect" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</p>
</form>
<script src="../../../vendor/jquery-1.12.4.js"></script>
<script>
$(function () {
// console.log($('[name=aaa]').val());
// console.log($('[name=text]').val());
// console.log($('[name=radio]:checked').val());//获取单选框
// console.log($('[name=select] option:selected').val()); //获取下拉选
// console.log($('[name=multiSelect]').val());
// console.log(
// $('[name="checkbox"]:checked').map(function () {
// return $(this).val();
// }).toArray()
// );
$('[name=text]').val('text')
$('[name=select]').val('2')
$('[name=radio]').val(['1'])
$('[name=checkbox]').val(['2'])
$('[name=multiSelect]').val(['1', '2'])
})
</script>
</body>