美文网首页
事件冒泡,阻止冒泡,事件委托,节点操作

事件冒泡,阻止冒泡,事件委托,节点操作

作者: 寻_4533 | 来源:发表于2019-06-19 20:03 被阅读0次

//事件冒泡

    $(function () {

$('.grandfather').click(function () {

alert(3);

        })

$('.father').click(function () {//点击son后事件会往上边传递,如果父元素有点击事件也会触发,一直往上传

            alert(2);

        })

$('.son').click(function (event) {//

            alert(1);

            console.log(event);

            console.log('x轴坐标'+event.clientX);

            //阻止冒泡

            event.stopPropagation();

            return false;//简写

        });

        //阻止右键菜单

        $(document).oncontextmenu(function (event) {

//阻止默认行为

            event.preventDefault()

})

})

//阻止冒泡

    $(function () {

return false;

    })

//事件委托 对大量的子元素操作的时候用 一种代理模式

    $(function () {//只绑定一次事件通过冒泡的方式处理

        $('.list').delegate('li','click',function () {//第一个参数是选择器,第二个是事件

            alert($(this).html());

            //取消委托

            $('.list').undelegate();

        })

})

//节点操作

    var $span = $('<span>元素</span>');

    $('#div1').append($span);//从后边添加子元素

    $span.appendTo('#div1');//也是从后边添加 同上

    $('#div1').prepend($span);//从前插入子元素

    $span.prependTo('#div1');

    $('#div1').before($span);//把span插入到div前边

    $span.insertBefore('#div1')

after()//插入到后边

    inserAfter()

remove()//删除

</script>

相关文章

网友评论

      本文标题:事件冒泡,阻止冒泡,事件委托,节点操作

      本文链接:https://www.haomeiwen.com/subject/udslqctx.html