我正在搞乱JavaScript,并注意到它this永远不会是原始的.我在说什么?让我解释.
以此功能为例.
function test(){
return typeof this;
}
test.call('Abc'); // 'object'
test.call(123); // 'object'
Run Code Online (Sandbox Code Playgroud)
他们既不是'object','string'也'number'不像我期望的那样.
经过一些混乱(并且搞乱了instanceof)之后,我想出了发生了什么. 'Abc'被转换为一个String对象,123并被转换为一个Number对象.
无论如何,我的问题是为什么会发生这种情况,以及如何将对象转换回原语?
我知道我可以使用(String)this或者(Number)this,但如果我不知道这种类型怎么办呢?
编辑:我试图这样做:
function element(){
var $e = $(this),
$d = $e.closest('div');
}
element.call('#myID');
Run Code Online (Sandbox Code Playgroud)
它不起作用. this是一个String对象,jQuery只是创建了一个对象集合,而不是使用选择器来搜索DOM.
我正在玩这个代码:http: //jsfiddle.net/VmVAq/
如您所见,在页面加载时,仅显示DIV 1.你可以注意到,样式是内联的所以我决定将它添加到标题:http: //jsfiddle.net/Ym96t/2/
这就是问题所在.现在在页面加载时,显示所有DIV,为什么?我是如何破解代码的?
如果您想在此处查看代码:
原版的:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function showonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
}
else {
$(this).hide(600);
}
});
}
</script>
</head>
<body>
<div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
<a id="myHeader1" href="javascript:showonlyone('newboxes1');" >show this one only</a>
</div>
<div class="newboxes" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #1</div>
<div style="border: 1px solid …Run Code Online (Sandbox Code Playgroud)