tiny_jquery.js
var $ = function (selector) {
var ele = document.querySelector(selector);
//返回当前元素的内容
ele.val = function () {
return ele.value;
}
//传入CSS样式,更改元素的样式
ele.css = function (css) {
if (typeof css === 'object') {
var str = '';
for(var k in css){ // {color: 'red', border: '1px solid blue'}
str =str.concat(k, ':', css[k], ';')
}
ele.style = str;
}
}
ele.html = (html) => {
var str = ele.innerHTML;
ele.innerHTML = str + html;
}
return ele;//返回当前元素
}
html文件需要引用上面的js文件
<script src="tiny_jquery.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>迷你jquery</title>
<script src="tiny_jquery.js"></script>
<script>
function test() {
//调用jQuery的方法
var username = $('#username').val();
console.log(username);
$('#username').css({color: 'red', border: '1px solid blue',background: 'pink'});
$('.mydiv').html('<p>新加入的内容</p>');
}
</script>
</head>
<body>
用户名:<input type="text" id="username" value="stars-one" >
<br><br>
<div class="mydiv">原来的内容,</div>
<button type="button" onclick="test()">点击添加新内容</button>
</body>
</html>