대답은 훨씬 더 복잡하다. 먼저 요소를 찾아야하므로 id
및 class
접근 방식은 이미 가지고 있지 않으면 작동하지 않습니다 (아래 type
솔루션 참조).는
// CHANGE SUBMIT STYLE
var foo = document.getElementById('submit');
foo.onmouseover = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
foo.onmouseout = function() {this.style.borderColor='#888888'; this.style.color='#888888';}
foo.onclick = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
하지만 다음도 작동합니다 :
찾기 class
기준 :
당신이 예를 클래스를 지정해야합니다 이 경우 <input type="submit" class="submit">
. getElementsByClass
이 type
을 찾지 못하면 class
을 찾습니다.
function getElementByType(node,type,tag) {
var els = node.getElementsByTagName(tag);
for (var x=0, x<els.length; x++) {
if (els[x].type && els[x].type.toLowerCase() == type) {
return els[x]
}
}
}
var foo = getElementByType(document.body, 'submit', 'input')
...
내가 무엇을 할 것은 :
<div id="externalElms">
(<script> here)
</div>
후 사용
<script type="text/javascript">
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("\b"+searchClass+"\b");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
// CHANGE SUBMIT STYLE
var foo = getElementsByClass(document.body, 'submit', 'input')[0];
foo.onmouseover = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
foo.onmouseout = function() {this.style.borderColor='#888888'; this.style.color='#888888';}
foo.onclick = function() {this.style.borderColor='#000000'; this.style.color='#000000';}
</script>
찾기 type
기준 : 다음 사용하는 경우는
당신은 type
에서 찾을 수 var foo = getElementByType(document.getElementById('externalElms'), 'submit', 'input')
페이지의 모든 요소를 거칠 필요가 없습니다.
이제 훨씬 더 명확 해졌습니다. 입력에 대한 ID를 추가 한 다음 document.getElementById 메소드를 사용했지만 입력 자체는 외부 JS 스크립트에 의해 작성됩니다. 그래서 대체 솔루션을 사용해보아야 할 것입니다. 고마워, 데이빗! – Dan
또 다른 아이디어 : 입력 (JS 사용)에 ID를 첨부 한 다음 document.getElementById를 사용하여 ID를 호출 할 수 있습니까? – Dan
@Dan : 더 빠른 옵션을 추가했지만'id'를 설정하기 전에 요소를 찾아야하므로'document.getElementById'를 사용하여 다시 액세스해야하지 않는 한 그럴 가치가 없을 수도 있습니다. – cryo