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="http://www.w3.org/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="http://www.baidu.com" 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="http://www.w3.org/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>