Angular解决IE和Firefox下button内部元素ng-click事件被屏蔽

如果我们在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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...