1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > angular 按下回车键触发事件

angular 按下回车键触发事件

时间:2024-03-05 13:29:02

相关推荐

angular 按下回车键触发事件

angularJs 按下回车键触发事件这个功能很简单,但是今天的却让我掉坑很久。。。。

由于我的页面上有两个不同方法都传$event事件,如search($event)和create($event);

html代码:

<input type="text" placeholder="支持空格及英文逗号分隔"

ng-model="ipAdress"

required

style="display: inline-block;height: 37px;width: 96%;float: left;"

ng-keypress="($event.which === 13)?search($event):0"/>

我用的是ng-keypress方法,search($event)是我想要按下回车触发的函数,传值$event是为了在search函数执行时阻止默认事件。

js处理:

function search($event){

//to do someing.........

$event.preventDefault();//阻止默认事件(如果不写这个create($event)函数里边的内容也会执行)

}

强调:这里必须用preventDefault()方法,而不是stopPrapagation();这两个是不同的;这里我给大家简单普及一下。

严格来说stopPropagation与preventDefault其实没什么关系,一个是停止传播事件,一个是阻止默认的行为(如<a>标签的地址跳转等)。

用下边例子给大家演示一下就知道了。

preventDefault()方法示例:<!DOCTYPE><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JS阻止链接跳转</title><script type="text/javascript"> function stopDefault( e ) { if ( e && e.preventDefault ) e.preventDefault(); else window.event.returnValue = false; return false; } </script> </head><body><a href="" id="testLink">百度</a> <script type="text/javascript"> var test = document.getElementById('testLink'); test.onclick = function(e) { alert('我的链接地址是:' + this.href + ', 但是我不会跳转。'); stopDefault(e); } </script></body></html>

stopPropagation()用法示例:<!DOCTYPE><HTML XMLns="/1999/xHTML" lang="gb2312"><head><title> 阻止JS事件冒泡传递(cancelBubble 、stopPropagation)</title><meta name="keywords" content="JS,事件冒泡,cancelBubble,stopPropagation" /><script>function doSomething (obj,evt) {alert(obj.id);var e=(evt)?evt:window.event;if (window.event) {e.cancelBubble=true;// ie下阻止冒泡 } else {//e.preventDefault(); e.stopPropagation();// 其它浏览器下阻止冒泡 }}</script></head><body><div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow"><p>This is parent1 div.</p><div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange"><p>This is child1.</p></div><p>This is parent1 div.</p></div><br /><div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;"><p>This is parent2 div.</p><div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;"><p>This is child2. Will bubble.</p></div><p>This is parent2 div.</p></div></body></HTML>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。