admin管理员组

文章数量:1387310

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?

本文标签: javascriptepreventDefault() is not working on div onclickStack Overflow