jQuery插入、添加和删除元素,事件和取消

2017-05-22  本文已影响92人  李悦之
1、addClass() removeClass()
$('div').find('h2').filter('.h2').addClass('.mother')

给选定的元素添加/删除class,这个方法的好用之处在于,可以用它来实现各类样式的切换。思路:提前把样式写好,放在一个class下面,选择合适的时机把它添加移除到相应的元素当中。

2、width() innerWidth() outerWidth()
console.log($('.father').width())   //元素本身宽度
console.log($('.father').innerWidth())  //包含了元素padding
console.log($('.father').outerWidth())  // 包含了padding和border
console.log($('.father').outerWidth(true))  //包含了padding border margin
3、jQuery中的插入元素的方法
$('.xxx').insertBefore($('.yyy'))

把.xxx的元素插入到.yyy的前面,注意这个时候返回的依然是.xxx的元素,这且.xxx这个元素的是剪切的过程,不是复制

相应的before()

$('div').before($('span'))

这个的意思就是在div的前面插入span,和insertBefore()刚好相反;两者语义不同,insertBefore()的语义更容易理解一点。需要注意的是两者的返回值,两者返回的都是前面的元素。

相应的:

insertAfter()  // after()
appendTo()  // append()
prependTo()  // prepend()

都是一样的逻辑

4.remove()和detach()
 let a = $('div').remove()
$('body').append(a)

在remove()以后依然会返回那个被删除掉的div,可以将它赋值给一个变量以后进行恢复使用。同时,detach()和remove()的区别在于,它会保留原本的操作行为,而remove不会保留这些东西。

5、事件绑定和取消
$('div').on('click mouseenter',function(){
    console.log('123')
})

$('div').on({
   'click' : function(){console.log('1')},
   'mouseover' : function(){console.log('2')}
})

可以同时添加多个事件,中间用空格分开。而可以像下面的那个样子,针对不同的事件触发不同的函数。

$('div').on({
      'click':function(){
        console.log('1')
        $('div').off('click')
      },
      'mouseover':function(){
        console.log('2')
      }
    })

同一段代码,如果添加了off()就是取消事件,如果是off()就是取消全部事件,如果是off('click')就是单独取消一个事件。

 $('div').on('click',function(){
      console.log('1')
    })
    $('div').off()

如果是这样写,那么这个事件根本就没有被执行就会被取消。注意off()的具体位置,在不同的位置会有不一样的结果。

上一篇下一篇

猜你喜欢

热点阅读