[英]ID Element return when giving as parameter
我正在為學校創建一個網站,我們在這里使用功能。 現在我遇到了一個小問題
我正在使用jquery來更改DOM,並制作了一個函數,您可以在其中選擇將元素添加到的位置。
像這樣:
function functioname(parameter){
console.log(parameter);
}
當我這樣調用此函數時:
functioname("#id");
我將返回“ #id”;
但是,如果我這樣稱呼它:
functioname (id);
我得到整個div和他的孩子們的回報。 怎么會這樣 為什么只在divs上工作呢?
我只是想知道這是如何工作的,這並不是一個真正的問題。
在此先感謝您能解釋一下這里發生的事情。
window.id
將找到其id
匹配的DOM元素。 例如, window.mydiv
將找到:
<div id="mydiv"></div>
但是,這不是推薦的做法。
通常,依靠它會導致代碼變脆。 例如,隨着新功能添加到Web平台,最終映射到該API的ID會隨時間變化。 代替此,使用document.getElementById()或document.querySelector()。
http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object
在第一個函數中,您傳遞字符串,在第二個示例中,您傳遞窗口對象。 與我們通過“ this”傳遞對象相同
<div onclick= " functionname(this); "> </div>
在這里,我們得到了函數內部的完整對象。
在代碼“ #id”的第一行中,您正在傳遞字符串。 正如您所說的,它也返回字符串。
在第二秒,您傳遞了您的代碼前面的對象ID。 這也許就是為什么您得到不同結果的原因。
讓我們看一下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中始終為true。 這就是為什么最后兩組測試結果相同的原因。 除非您使用var prop;
聲明了prop,否則prop === window.prop
也很重要var prop;
。 這是因為,除非另有說明,否則JavaScript始終秘密地在window
變量上使用special關鍵字using
。
所有瀏覽器都使用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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.