<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<style>
.left p,
.right p {
width: 500px;
height: 80px;
padding: 5px;
margin: 5px;
float: left;
border: 1px solid #ccc;
}
.left p {
background: #bbffaa;
}
.right p {
background: yellow;
}
select {
height: 100px;
}
</style>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
</head>
<body>
<h2>input與textarea</h2>
<p class="left">
<h4>測(cè)試一</h4>
<p class="aaron">
選中文字:input
<input type="text" value="慕課網(wǎng)" />
</p>
<button id="bt1">觸發(fā)input元素的select事件</button>
<h4>測(cè)試二</h4>
<p class="aaron">
textarea:
<textarea rows="3" cols="20">用鼠標(biāo)選中文字</textarea>
</p>
</p>
<script type="text/javascript">
//監(jiān)聽(tīng)input元素中value的選中
//觸發(fā)元素的select事件
$("input").select(function(e){
alert(e.target.value)
})
$("#bt1").click(function(){
$("input").select();
})
//監(jiān)聽(tīng)textarea元素中value的選中
$('textarea').select(function(e) {
alert(e.target.value);
});
</script>
</body>
</html>
上面代碼運(yùn)行時(shí),為什么在點(diǎn)擊按鈕后,會(huì)彈出來(lái)3次alert?實(shí)在不明白,求大神指點(diǎn),謝謝啦(∩_∩)
閉關(guān)修行中......
在FireFox里,你的代碼就是正常的;
在Chrome里,就會(huì)出現(xiàn)響應(yīng)三次的情況;
說(shuō)實(shí)話(huà)我剛才測(cè)試了一下,雖然也沒(méi)弄明白具體原理,但是找了解決方法和一些新發(fā)現(xiàn);
在select()
函數(shù)里用e.preventDefault()
可以阻止多次響應(yīng);
當(dāng)input
的value
為空的時(shí)候只會(huì)響應(yīng)兩次;
多余的select()
響應(yīng)會(huì)在click()
方法執(zhí)行完之后執(zhí)行;
希望對(duì)你有幫助
https://api.jquery.com/select/
The method for retrieving the current selected text differs from one
browser to another. A number of jQuery plug-ins offer cross-platform
solutions.
Jquery官方文檔給出的解釋。不同瀏覽器的表現(xiàn)不一致。
測(cè)試多次發(fā)現(xiàn):
看起來(lái)好像 jQuery
可能做了什麼造成觸發(fā)第三次
input.select()
setTimeout
配合原生方法可以只觸發(fā)一次$("#bt1").click(function(){
setTimeout(function() { input.select(); }, 0)
})
原因不明,追查中...在這之前可能先使用 setTimeout
方法,嚴(yán)重懷疑是 Chrome
的 bug