我在这方面运气不太好。 我正在尝试确定一个变量是否为空。
$('#content').mouseup(function() {
var selection = getSelected();
if (typeof(selection) !=='undefined') {
alert(selection);
}
});
这段代码的作用是获取用户选择的任何文本--但即使用户只是在div上放开鼠标,它也会显示一个空警告。
我在这方面运气不太好。 我正在尝试确定一个变量是否为空。
$('#content').mouseup(function() {
var selection = getSelected();
if (typeof(selection) !=='undefined') {
alert(selection);
}
});
只需要说:
if (selection) {
alert(selection);
}
在JavaScript中,简单的真/假测试结果为true(真),如果成员被定义、非null(非空),非false(非假),非空字符串或者非零。
另外,在JavaScript中,某些值可以等于undefined(undefined表示没有这样的命名对象存在)。例如:
var x = undefined;
alert(x===undefined); /* true; */
alert(x); /* false */
x=1;
alert(x); /* true */
alert(y===undefined); /* reference error - there's nothing called y */
alert(y); /* reference error */
alert(typeof y === "undefined"); /* true */
如下方评论所述,如果您不确定某个变量是否存在,应该先使用typeof
进行测试。
ReferenceError
。 如果你需要确保变量存在并且具有某些真值:if (typeof selection !== 'undefined' && selection) ...
- Reidalert(selection)
会导致错误。如果你得到一个空的警告框,那是因为selection
的值是一些空白但不是空字符串的东西。也许它是一个单独的空格或其他东西。我不知道那个函数返回什么,但它没有返回一个空字符串,否则选择就不会显示。请参见:http://jsfiddle.net/2mm5n/ - Jamie Treworgywindow.getSelection
函数),您可以检查isCollapsed
属性来查看选择是否为空:if (!selection.isCollapsed) ...
if (selection) {
alert(selection);
}
getSelected()
函数? - Håvard