변수를 사용하여 변수 값과 동일한 객체를 호출 할 수 있습니까?
-
13-09-2019 - |
문제
원래 GetElementById에서 온 문자열이 전달되는 함수가 있다고 가정 해 봅시다. 그리고 그 문자열 값과 같은 이름을 가진 개체가 있는데, 그 개체를 호출 할 수있는 방법이 있습니까? 요소의 ID에서 해당 값을 얻을 때까지 원하는 객체를 알지 못합니다.
예를 들어:
StartingFunction(SomeID){
someVariable = document.getElementById(SomeID).id
somefuntion(someVariable)
}
someFunction(ElementID){
// need to call Object.Value of whichever object is named the same as the value of
//ElementID here
}
ElementId.Value는 분명히 작동하지 않기 때문에 ElementId는 단지 변수가 아니라 객체가 아니기 때문에 ...
해결책
요소를 약간의 기능으로 직접 전달할 수 있습니다.
예를 들어:
StartingFunction(SomeID){
var element = document.getElementById(SomeID);
somefuntion(element);
}
someFunction(element){
alert(element.id);
alert(element.value);
// Any other processing you want to do with element
}
또는 ID에서 요소를 얻을 수 있어야하는 경우 getElementById
someFunction(id) {
var element = document.getElementById(id);
alert(element.value);
// Any other processing you need to do with the element DOM object
}
다른 팁
당신이 요소라고 부르는 것은 문서를 전달하기 때문에 실제로 요소 자체입니다.
함수가 전역 범위에 있으면 그냥 할 수 있습니다 window[ElementID]
예를 들어:
someFunction(ElementID){
return window[ElementID].value;
}
그렇게하지 마십시오. 이것은 나쁜 디자인이며 길을 따라 엄청난 통증과 찾기 어려운 버그로 이어질 것입니다.
대신, 참조하려는 모든 객체가있는 글로벌 객체를 사용하십시오.
var valueMap = new Object();
function setValue(id, valueObject) {
valueMap[id] = valueObject;
}
function someFunction(id) {
return valueMap[id].Value;
}
이것은 말이되지 않습니다 :
someVariable = document.getElementById(SomeID).id
당신은 id nodicid로 요소의 ID를 가져오고 있습니다 ... 왜 그냥 사용하지 않습니까?
id sodiceid가있는 객체의 값 속성을 원한다면 다음과 같이하십시오.
document.getElementById(SomeID).value
제휴하지 않습니다 StackOverflow