答案要複雜得多,如果由一個外部JavaScript腳本生成的元素。您需要首先找到元素,因此id
和class
方法無法工作,除非它們已經有一個 - 請參閱下面的type
解決方案。
查找id
:
優先下面,你需要一個ID添加到輸入提交例如<input type="submit" id="submit">
通過引用它:
// 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
。
<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
找到,如果你使用以下命令:
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>
然後使用var foo = getElementByType(document.getElementById('externalElms'), 'submit', 'input')
,因此它不必瀏覽頁面上的每個元素。
現在它變得更清晰了。我會爲輸入添加一個ID,然後使用document.getElementById方法,但輸入本身由外部JS腳本創建。所以,我不得不嘗試替代解決方案。謝謝,大衛! – Dan 2010-04-12 04:00:34
另一個想法:不可能先將ID附加到輸入(使用JS),然後通過document.getElementById調用它? – Dan 2010-04-12 04:11:47
@Dan:增加了一個更快的選項,但是你需要在設置id之前找到元素,所以它可能不值得,除非你需要使用'document.getElementById'再次訪問它。 – cryo 2010-04-12 04:33:26