【发布时间】:2011-09-04 11:06:11
【问题描述】:
我无法解释下面代码的行为。这是我的整个脚本
<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var tmpText = '';
$(document).ready(function(){
tmpText = '';
$('#btn_bold').click(function(){alert(tmpText);});
$('textarea').bind('mouseup', function(){
tmpText = '';
if(window.getSelection){
tmpText = window.getSelection();
}else if(document.getSelection){
tmpText = document.getSelection();
}else if(document.selection){
tmpText = document.selection.createRange().text;
}
//tmpText = 'hello world';
alert(tmpText);
});
});
</script>
</head>
<body>
<button type="button" id="btn_bold">click</button>
<textarea>This is some text</textarea>
</body>
</html>
尝试以下操作:
1) 使用鼠标突出显示文本区域中的文本。您会注意到 javascript 会提醒您选择的文本。
2) 按下点击按钮。你会注意到 javascript 会提醒你一个空字符串。
不要取消注释tmpText = 'hello world'; 并重复上述步骤。这一次,您会注意到步骤 1) 和 2) 都会提醒您“hello world”。
为什么在第一个实验中,步骤 2) 没有提醒您与步骤 1) 相同的文本?
我正在谷歌浏览器中测试
【问题讨论】:
标签: javascript jquery