[英]How do I return the id of a DOM element using javascript, not the value of the element
[英]How do I refernce a DOM element by ID using a variable in Javascript?
如果我的 HTML 中有幾個像這樣的 div
<div id="div_1"></div>
<div id="div_2"></div>
<div id="div_3"></div>
在我的 JavaScript 中,如何使用變量引用它們?
// Using Jquery to assign the element to the variable name
$div_1 = $(div_1);
$div_2 = $(div_2);
$div_3 = $(div_3);
// set the CSS for each div
for (i = 1; i <= 3; i++) {
$div_[i].css({'left': 100 +'px'});
}
ID 只是字符串,因此可以這樣構建它們:
id = 2;
e = document.getElementById('div_' + id);
如果您的意思是存儲每個找到的元素,那么您需要一個數組:
divs = [];
divs[1] = $('#div_1');
divs[2] = $('#div_2');
您可以創建變量保存的所有元素,使用.filter()
來選擇一個元素具有特定全id
或id
與特定的數字或字母字符結尾
// all `div` elements having `id` beginning with `"div"`
var divs = $("div[id^=div]");
// select element having `id` ending with `"2"`:`"div_2"` from `divs` collection
var div_2 = divs.filter("[id$=2]");
您可以使用 div 的“id”屬性並獲得如下參考:
$div_1 = $("#div_1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.