作为参数给出时,ID元素返回

时间:2014-12-18 14:39:57

标签: javascript jquery html css

我正在为学校建立一个网站,我们在那里工作。现在我得到了一个小问题

我正在使用jquery来更改DOM并创建了一个函数,您可以在其中选择要添加元素的位置。

这样的事情:

function functioname(parameter){

console.log(parameter);
}

当我这样调用这个函数时:

functioname("#id");

我将返回“#id”;

但如果我这样称呼它:

functioname (id);

我得到整个div和他的孩子们的回报。怎么会发生这种情况? 为什么只能用div工作呢。

这不是一个问题,我只是想知道它是如何工作的。

如果有人能解释这里发生的事情,请提前致谢。

4 个答案:

答案 0 :(得分:2)

window.id将找到与id匹配的DOM元素。例如,window.mydiv会找到:

<div id="mydiv"></div>

但是,这不是推荐的做法。

  

作为一般规则,依赖于此将导致代码脆弱。例如,随着新功能添加到Web平台,哪些ID最终映射到此API可能会随着时间的推移而变化。而不是这个,使用document.getElementById()或document.querySelector()。

http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object

答案 1 :(得分:0)

在第一个函数中传递字符串,在第二个示例中,您传递的是窗口对象。与我们使用“this”

传递对象相同
<div onclick= " functionname(this); "> </div>

这里我们得到函数内的完整对象。

答案 2 :(得分:0)

在第一行代码“#id”中传递字符串。它也像你说的那样返回字符串。

在第二步中传递您在代码中先前的对象ID。这可能就是为什么你得到了不同的结果。

答案 3 :(得分:0)

让我们看一下window对象。该窗口非常酷,它允许您从动态的任何地方声明全局变量。以下面的代码为例

//the following three lines of code do the same thing
//create a global variable and store a value in it
window.a = 1;
window["b"] = 2;
var c = 3; //this one is most used though

function g() {
    //the following three lines of code do not do the same thing
    window.d = 4; //global
    window["e"] = 5; //global
    var f = 6; //local
}

g();

console.log(a); //prints 1
console.log(b); //prints 2
console.log(c); //prints 3
console.log(d); //prints 4
console.log(e); //prints 5
try {
    console.log(f); //ERROR
} catch (err) {
    console.log(err);
}

console.log(window.a); //prints 1
console.log(window.b); //prints 2
console.log(window.c); //prints undefined
console.log(window.d); //prints 4
console.log(window.e); //prints 5
console.log(window.f); //prints undefined

console.log(window["a"]); //prints 1
console.log(window["b"]); //prints 2
console.log(window["c"]); //prints undefined
console.log(window["d"]); //prints 4
console.log(window["e"]); //prints 5
console.log(window["f"]); //prints undefined

重要的是要知道obj.prop === obj["prop"]在JavaScript中始终是正确的。这就是为什么最后两组测试具有相同的结果。同样重要的是prop === window.prop,除非您使用var prop;声明道具。这是因为JavaScript始终在using变量上秘密使用特殊关键字window,除非另有说明。

所有浏览器都使用document.getElementByID通过id提供DOM元素,但有些浏览器足以为您设置一些变量,因此您无需编写所有代码。想象一下,浏览器在任何脚本执行之前运行此脚本

(function(context) {
    var tags = document.getElementsByTagName("*");
    for (var i = 0; i < tags.length; i++) {
        var tag = tags[i];
        if (tag.id) {
            context[tag.id] = tag;
        }
    }
}(window));

使用带有id的标记填充窗口变量/全局范围。

以下是一些例子。 http://jsfiddle.net/Lk345zez/