最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - e.preventDefault() is not working on div onclick - Stack Overflow

programmeradmin2浏览0评论

preventDefault() is not working on div onclick, i tried preventDefault and stopImmediatePropagation also nothing works, please see the below sample.

<title></title>

<script src="scripts/jquery-1.5.2.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $().ready(function () {
        $("div").click(function (e) {
            e.preventDefault();
            //e.stopImmediatePropagation();
            return false;
        });

        //$("div").bind("click", function (e) { e.stopImmediatePropagation(); return false; });

    });

</script>

<div onclick="alert('1');">

    Sample text

</div>

preventDefault() is not working on div onclick, i tried preventDefault and stopImmediatePropagation also nothing works, please see the below sample.

<title></title>

<script src="scripts/jquery-1.5.2.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $().ready(function () {
        $("div").click(function (e) {
            e.preventDefault();
            //e.stopImmediatePropagation();
            return false;
        });

        //$("div").bind("click", function (e) { e.stopImmediatePropagation(); return false; });

    });

</script>

<div onclick="alert('1');">

    Sample text

</div>

Share Improve this question edited Sep 26, 2012 at 2:10 Eli 14.8k5 gold badges61 silver badges77 bronze badges asked Apr 22, 2011 at 6:46 user720149user720149 611 silver badge4 bronze badges 2
  • How do you know its not working, i.e. what default behaviour are you seeing or ancestor element's events are you observing? – alex Commented Apr 22, 2011 at 6:50
  • You cannot ensure your binded event will be the first to be run. Did you tried $('div').removeAttr('onclick') ? – regilero Commented Apr 22, 2011 at 7:44
Add a ment  | 

1 Answer 1

Reset to default 5

There is no default behaviour of clicking on a div. What are you trying to prevent?

Also event.stopPropagation() is to stop the event from bubbling up ancestors and triggering their event handlers. What is it triggering in your case?

发布评论

评论列表(0)

  1. 暂无评论