html和text的区别
☆html用于获取第一个匹配元素的HTML内容或文本内容
/* html用于设置所有匹配元素的HTML内容或文本内容 */
/* text用于获取所有匹配元素的文本内容 */
/* text用于设置所有匹配元素的文本内容 */
console.log( $('div').html() );
/* text只能打印出文字,不能打印出标签 */
console.log( $('div').text('<h1>123</h1>') );
获取表单的值
$('button').click(function(){
console.log($('input').val());
})
基本操作和获取值
function fn(){
if($(this).hasClass('div1')){
$(this).removeClass('div1')
}else{
$(this).addClass('div1')
}
}
$('div').mouseover(function(){
fn.call(this)
})
$('div').mouseout(function(){
fn.call(this)
})
hover只写一个方法,鼠标移入和移出都会执行一次
$('div').hover(function () {
$(this).toggleClass('div1')
})
$('div').click(function () {
$('input').val($('div').text().trim())
})
节点操作1
通过选择器获取节点
//console.log($('div'));
把DOM节点转化成jQuery节点
/* let div1=document.getElementsByTagName('div')[0]
console.log($(div1)); */
使用HTML字符串创建jQuery节点
let h1=$('<h1 style="color:red">我爱H1</h1>');
console.log(h1);
html传的是字符串
$('div').html(h1)
/* let h1=document.createElement('h1');
h1.innerText='我爱中国';
console.log(h1);
document.querySelector('div').innerHTML=h1.innerHTML */
节点操作2
<button class="a1">在内部在后面添加</button>
<button class="b1">在内部在上面添加</button>
<button class="aa">向后生成头像</button>
<button class="bb">向前生成头像</button>
$('.b1').click(function(){
$(a).prepend(b) 表示将b前置插入a中
$('ul').prepend('<li>我是li的前端</h1>')
$(b).prependTo($(a)) 表示将b前置插入a中
})
$('.a1').click(function(){
原生只能插入节点
(a).append(b) 将b插入a中
$('ul').append('<li>我是li</li>');
//$('<li>我是li</li>').appendTo($('ul'));
})
元素外部插入同辈节点
★ after和before都是在自身的后面添加,并不是最后面添加
$('div').click(function(){
//$(a).after(b) 将b插入a之后
$(this).after($('<h1>爱爱爱</h1>'))
//$(b).insertAfter(a) 将b插入a之后
$(this).before($('<h1>我我我</h1>'))
})
/* 点击按钮 随机生成一个头像,插入到div中 */
let arr=['images/1.jpg','images/2.jpg','images/3.jpg'];
/* $('.tx').click(function(){
var i=Math.floor(Math.random()*(2-0+1)+0);
$('div').append('<img src="'+arr[i]+'">')
$('div').prepend('<img src="'+arr[i]+'">')
}) */
$('.aa').click(function(){
fn('向前')
})
$('.bb').click(function(){
fn('向后')
})
function fn(msg){
var i=Math.floor(Math.random()*(2-0+1)+0);
let img=$('<img src="'+arr[i]+'">');
if(msg=='向后'){
$('div').append(img)
}
if(msg=='向前'){
$('div').prepend(img)
}
}