jQuery--DOM操作(二)
一锨咙、元素的特性颅筋、屬性
特性 attributes vs 屬性 properties
- attributes:值為 string
- properties:值為 string、boolean、number鞍恢、object
- 如果 attributes 是本來(lái)在DOM對(duì)象中就存在的,attributes和properties 的值會(huì)同步每窖;
- 如果 attributes 是本來(lái)在DOM對(duì)象中就存在的帮掉,但是類型為Boolean,那么attributes和properties 的值不會(huì)同步窒典;
- 如果 attributes 不是DOM對(duì)象內(nèi)建的屬性蟆炊,attributes和properties 的值不會(huì)同步;
代碼示例:
<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 所以對(duì)于class瀑志,獲取屬性時(shí)使用className涩搓,獲取特性直接使用class
});
</script>
</body>
二、使用jQuery操作元素的屬性劈猪、特性和數(shù)據(jù)
1.操作元素的特性
? 獲取特性的值:attr(name):獲取第一個(gè)元素的值
? 設(shè)置特性的值: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)
? 設(shè)置屬性的值: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是一個(gè)jQuery對(duì)象
console.log(checkbox.prop('checked')); //false
console.log(checkbox.checked);//undefined
//轉(zhuǎn)換為DOM對(duì)象就可以獲取到了
console.log(checkbox.get(0).checked);//false
console.log(checkbox.attr('checked')); //undefined
console.log(checkbox.get(0).tabindex);//undefined dom里面使用全小寫(xiě)昧甘,必須使用駝峰形式
console.log(checkbox.get(0).tabIndex);//1
console.log(checkbox.prop('tabindex')); //1
console.log(checkbox.prop('tabIndex'));//屬性區(qū)分大小寫(xiě) ,特性不區(qū)分
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結(jié)構(gòu)沒(méi)有改變岸霹,只是屬性改變了
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.在元素中存取數(shù)據(jù)
? 獲取數(shù)據(jù)的值:data([name])
? 設(shè)置數(shù)據(jù)的值:data(name, value) data(object)
? 刪除數(shù)據(jù):removeData([name])
? 判斷是否有數(shù)據(jù):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>
三、在頁(yè)面中操作 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>
②獲取或設(shè)置 style
? css(name, value)
? css(properties)
? css(name)
③獲取或設(shè)置元素尺寸
? width(value):只針對(duì)該對(duì)象集合里的第一個(gè)元素将饺,而不是所有元素
? height(value)
? innerHeight(value):包含內(nèi)邊距贡避,不包含邊框和外邊距
? innerWidth(value)
? outerHeight ([includeMargin]):包含內(nèi)邊距和邊框痛黎,不一定包含外邊距,想要包含外邊距刮吧,傳入布爾參數(shù)湖饱,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', //如果使用-形式杀捻,不是駝峰形式井厌,需要用引號(hào)括起來(lái)
height: 200, //使用px作為默認(rèn)的
border: '10px solid #000',
marginTop: 100,
mArGinLeft: 100,
width: '+=200'
});
//通過(guò)函數(shù)設(shè)置height index:索引值,value:當(dāng)前height的值
element.css('height', function(index, value) {
console.log(value); //200px
return parseInt(value, 10) + 50; //帶有單位致讥,所以要進(jìn)行轉(zhuǎn)換
});
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 如果是百分比或其他的單位,會(huì)自動(dòng)轉(zhuǎn)換為相應(yīng)的像素
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>
④獲取或設(shè)置位置和滾動(dòng)
? offset(coordinates):返回對(duì)象集合第一個(gè)元素
? 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 相對(duì)于文檔
console.log(element.position());//相對(duì)于父元素
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.修改元素內(nèi)容
①獲取或設(shè)置元素內(nèi)容
? 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 只對(duì)html第一個(gè)元素起作用
console.log(elements.text());//item-1item-2item-3item-4item-5item-6item-7item-8item-9 對(duì)jQuery對(duì)象集合里的所有元素都起作用
console.log(elements.html('<strong>123</strong>'));
//console.log(elements.text('<strong>123</strong>'));
console.log(elements.html('<script>alert("123")<\/script>'));//包含script時(shí)需要轉(zhuǎn)義
});
</script>
</body>
②移動(dòng)或插入元素
? 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">新聞標(biāo)題-1</li>
<li class="item2">新聞標(biāo)題-2</li>
<li class="item3">新聞標(biāo)題-3</li>
<li class="item4">新聞標(biāo)題-4</li>
<li class="item5">新聞標(biāo)題-5</li>
<li class="item6">新聞標(biāo)題-6</li>
<li class="item7">新聞標(biāo)題-7</li>
<li class="item8">新聞標(biāo)題-8</li>
<li class="item9">新聞標(biāo)題-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')) //移動(dòng)到元素的最后
// element.append($('.item1'))
// element.append('<p>p1</p>', ['<p>p2</p>', $('h2')], $('.item1'))
//element.append($('h2'))
$('h2').appendTo(element);//等價(jià)的
});
</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]):綁定的數(shù)據(jù)和事件都會(huì)被移除
? detach([selector]):移除后還會(huì)保留事件和數(shù)據(jù)
? empty():可以保留元素本身垢袱,清除干凈元素內(nèi)容
代碼示例:
<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>
⑤復(fù)制和替換元素
? 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">新聞標(biāo)題-1</li>
<li class="item2">新聞標(biāo)題-2</li>
<li class="item3">新聞標(biāo)題-3</li>
<li class="item4">新聞標(biāo)題-4</li>
<li class="item5">新聞標(biāo)題-5</li>
<li class="item6">新聞標(biāo)題-6</li>
<li class="item7">新聞標(biāo)題-7</li>
<li class="item8">新聞標(biāo)題-8</li>
<li class="item9">新聞標(biāo)題-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)
都是執(zhí)行了破壞性操作墓拜,在鏈?zhǔn)秸Z(yǔ)法中使用他們的時(shí)候,如果要選擇先前選擇的元素请契,需要使用end()
⑥處理表單元素值
? val():設(shè)置值
? 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>