如果我们在button元素内部有其它的子元素并且绑定点击事件,比如:
而我们的代码是这样的:
<body ng-controller="ctrl">
<script> angular.module("app",[]) .controller("ctrl",function($scope){ $scope.sayButton = function(e){ alert('button'); }; $scope.saySpan = function(e){ alert('span'); }; }) </script>
<button class="btn btn-default btn lg" ng-click="sayButton($event)">
Button
<span class="star glyphicon glyphicon-star" ng-click="saySpan($event)"></span>
</button>
</body>
这种情况下 chrome下点击span元素,会提示两个,即’span’和’button’,而对于IE则只提示’button’。(点击button均只提示’button’)
解决IE的处理点击事件错误的方式就是找“别的元素”来代替”button”元素,”狸猫换太子“。所以代码就变成了这样:
<div class="btn btn-default btn lg" ng-click="sayButton($event)">
Button
<span class="star glyphicon glyphicon-star" ng-click="saySpan($event)"></span>
</div>
这样结果对于chrome和IE结果都是一样的,点击span元素先提示’span’后提示’button’,点击button元素只提示’button’。
还有个问题就是阻止事件冒泡了,解决方法只需要在函数最后添加e.stopPropagation();
这句代码,所以最终我们的结果就是:
<body ng-controller="ctrl">
<script> angular.module("app",function($scope){ $scope.sayButton = function(e){ alert('button'); e.stopPropagation(); }; $scope.saySpan = function(e){ alert('span'); e.stopPropagation(); }; }) </script>
<div class="btn btn-default btn lg" ng-click="sayButton($event)">
Button
<span class="star glyphicon glyphicon-star" ng-click="saySpan($event)"></span>
</div>
</body>
效果图:(IE下)
Chrome下:
博客写到这FireFox也终于打开了,顺便看看效果:
FireFox下:
源代码:https://github.com/justforuse/Pro_Angular-demo/tree/master/button-inner
此文档的作者:justforuse
Github Pages:justforuse