為什么我點擊了按鈕以后,會觸發(fā)三次alert窗口呢
<!DOCTYPE html>
<html>
<head>
? ? <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
? ? <title></title>
? ? <style>
? ? .left div,
? ? .right div {
? ? ? ? width: 500px;
? ? ? ? height: 80px;
? ? ? ? padding: 5px;
? ? ? ? margin: 5px;
? ? ? ? float: left;
? ? ? ? border: 1px solid #ccc;
? ? }
? ??
? ? .left div {
? ? ? ? background: #bbffaa;
? ? }
? ??
? ? .right div {
? ? ? ? background: yellow;
? ? }
? ??
? ? select {
? ? ? ? height: 100px;
? ? }
? ? </style>
? ? <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
? ? <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
? ? <h2>input與textarea</h2>
? ? <div class="left">
? ? ? ? <h4>測試一</h4>
? ? ? ? <div class="aaron">
? ? ? ? ? ? 選中文字:input
? ? ? ? ? ? <input type="text" value="慕課網(wǎng)" />
? ? ? ? </div>
? ? ? ? <button id="bt1">觸發(fā)input元素的select事件</button>
? ? ? ??
? ? ? ? <h4>測試二</h4>
? ? ? ? <div class="aaron">
? ? ? ? ? ? textarea:
? ? ? ? ? ? <textarea rows="3" cols="20">用鼠標(biāo)選中文字</textarea>
? ? ? ? </div>
? ? </div>
?
? ? <script type="text/javascript">
? ? //監(jiān)聽input元素中value的選中
? ? //觸發(fā)元素的select事件
? ? $("input").select(function(e){
? ? ? ? alert(e.target.value)
? ? })
? ? $("#bt1").click(function(){
? ? ? ? $("input").select();
? ? })
? ? //監(jiān)聽textarea元素中value的選中
? ? $('textarea').select(function(e) {
? ? ? ? alert(e.target.value);
? ? });
? ? </script>
</body>
</html>
2017-09-14
因為瀏覽器有默認(rèn)行為,當(dāng)你點擊按鈕時第一次是觸發(fā)了select事件,第二次就是默認(rèn)行為,默認(rèn)行為會選中input的文本,就又觸發(fā) 了input元素的select事件,在select的回調(diào)函數(shù)中添加e.preventDefault()就可以取消默認(rèn)行為了
2019-03-20
這個e.preventDefault(),函數(shù)是添加再第一個$里的。