版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011240016/article/details/84191565
<!DOCTYPE html>
<html>
<head>
<title>jQuery Crash Course | DOM Manipulation</title>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<style>
body{
font-size: 17px;
font-family: arial;
background: #f4f4f4;
line-height: 1.5em;
}
header{
background:#333;
color:#fff;
padding:20px;
text-align: center;
border-bottom: 4px #000 solid;
margin-bottom: 10px;
}
#container{
width:90%;
margin:auto;
padding:10px;
}
.myClass {
color:blue;
background:black;
}
</style>
</head>
<body>
<header>
<h1>jQuery| DOM Manipulation</h1>
</header>
<div id="container">
<button id="btn1">Button 1</button>
<p class="para1">This is a paragraph</p>
<p class="para2">This is another paragraph</p>
<div id="myDiv"></div>
<input type="text" id="newItem">
<ul id="list">
<!-- <li>List Item 1</li> -->
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
</ul>
<a href="http://google.com">Google</a>
<ul id="users"></ul>
</div>
<script>
$(document).ready(function(){
// $('.para1').css('color', 'red')
// $('p.para1').css('color', 'red') // 和上面这个等效
$('p.para1').css({color: 'red', background:'#ccc'}); // 配置文件的形式
// 添加--移除css属性
// $('p.para2').addClass('myClass')
// $('p.para2').removeClass('myClass')
// 通过按钮事件来控制CSS样式
$('#btn1').click(function(){
$('p.para2').toggleClass('myClass')
});
// 与原生的js设置textContent相同
$('#myDiv').text('Hello World');
// innerHTML,用这个会覆写
$('#myDiv').html('<h3>Hello World</h3>')
// 直接在ul后面添加元素
$('ul').append('<li>Append List Item</li>')
// 在ul的前面添加元素
$('ul').prepend('<li>Prepend List Item</li>')
// 将段1改到段2后面
$('.para1').appendTo('.para2')
$('.para1').prependTo('.para2')
// 前后添加元素
$('ul').before('<h4>Hello</h4>')
$('ul').after('<h4>World</h4>')
// 清空元素,ul本身还在
// $('ul').empty()
// 从DOM树中解除ul,元素看不到了
// $('ul').detach()
// 通过jQuery为元素添加属性
$('a').attr('target','_blank')
// 获取属性
// alert($('a').attr('href'))
// 移除属性
// $('a').removeAttr('target')
// $('p').wrap('<h3>')
// $('p').wrapAll('<h3>')
// 为输入框添加监听事件
$('#newItem').keyup(function(e) {
var code = e.which; // 获取按键数字
console.log(code);
if(code == 13){
e.preventDefault();
$('ul').append('<li>' + e.target.value + '</li>')
}
})
var myArr = ['Ada', 'Bob', 'Cherry']
// jQuery对数组的遍历方式
$.each(myArr, function(i,val){
// console.log(i, val)
$('#users').append('<li>' + val + '</li>')
});
var newArr = $('ul#list li').toArray();
// console.log(newArr)
// $.each(newArr, function(i, val) {
// console.log(val.innerHTML)
// });
// 或者使用Lambda表达式也可以,效果相同
$.each(newArr, (i,val) => console.log(val.innerHTML))
});
</script>
</body>
</html>
这里面大多数都可以从原生的JS语法那里直观看出来,不过对于数组的遍历是值得重点关注的:
$.each(newArr, (i,val) => console.log(val.innerHTML))
$.each
语法。
END.