我的项目中有以下代码片段
<div class="form-horizontal well text-center" id="func_85" ng-if="prmissionlist.indexOf('chkfunction_85') >= 0">
<button class="btn btn-primary" type="button" id="btn_branch_save">
Save
</button>
<button class="btn btn-primary" type="button" id="btn_new_branchcancel">
CANCEL
</button>
</div>
但是按钮单击在 ng-if
div 内不起作用(按钮单击是使用 jQuery 选择器编写在 js 文件中。)
最佳答案
出现此问题的原因是 ng-if如果条件为 true,则动态将元素添加到 DOM,jquery Direct 事件 (.click()) 无法添加到动态添加的元素,因此您必须使用委托(delegate)事件 ( .on() ) 才能使其在动态添加的元素上工作元素。
Refer link for more informations on direct and delegate events
将 Jquery 点击事件替换为 .on()
$('.form-horizontal').on('click','#btn_branch_save',function(){
alert('dsfds');
});
作为替代方案,您还可以使用 ng-show它会在 DOM 加载时创建元素,并且只会将可见性应用为隐藏,但是在 Jquery 中使用委托(delegate)事件总是好的。
但是,我仍然想知道为什么你需要同时使用 Jquery 和 Angular,这并不是什么好的做法。
关于javascript - 按钮的 Jquery 单击事件在 ng-if div 内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844031/