2014-12-29 27 views
0

的作品的腳本:getElementByClassName的地方不工作的getElementById沒有(支持的瀏覽器)

function getEventTarget(e) { 
    e = e || window.event; 
    return e.target || e.srcElement; 
} 
var ul = document.getElementById('commandList'); 
ul.onclick = function(event) { 
    var target = $(getEventTarget(event)).clone().children().remove().end().text(); 
    document.getElementById('inputCommand').value = target; 
}; 

var interface = '/cgi-bin/CGIProxy.fcgi?cmd='; 
var protocol = 'http://'; 
var host, command, access, commandUrl; 

$('.sendCommand').click(function() { 
    host = $('#cameraLocation').val(); 
    access = $('#cameraAccess').val(); 
    command = $('#inputCommand').val() + $('#inputParam').val(); 
    commandUrl = protocol + host + interface + command + access;     
    $('#showUrl').html(commandUrl); 
    $('#showResult').attr('src', commandUrl); 
}); 

當我改變document.getElementByIddocument.getElementsByClassName(有問題的元素既有IDClass"commandList")的腳本執行不工作了,我錯過了什麼?謝謝!

新腳本:

function getEventTarget(e) { 
    e = e || window.event; 
    return e.target || e.srcElement; 
    } 
var ul = document.getElementsByClassName('commandList'); 
ul.onclick = function(event) { 
    var target = $(getEventTarget(event)).clone().children().remove().end().text(); 
    document.getElementById('inputCommand').value = target; 
    }; 

var interface = '/cgi-bin/CGIProxy.fcgi?cmd='; 
var protocol = 'http://'; 
var host, command, access, commandUrl; 

$('.sendCommand').click(function() { 
    host = $('#cameraLocation').val(); 
    access = $('#cameraAccess').val(); 
    command = $('#inputCommand').val() + $('#inputParam').val(); 
    commandUrl = protocol + host + interface + command + access;     
    $('#showUrl').html(commandUrl); 
    $('#showResult').attr('src', commandUrl); 
}); 

回答

1

getElementsByClassName()返回元件的NodeList,而getElementById()(和querySelector())返回單個節點。

要對類似數組的NodeList進行操作,您必須遍歷NodeList中包含的每個元素並分別指定每個元素的操作;例如:

Array.prototype.forEach.call(document.getElementsByClassName('whatever'), function (elem) { 
    elem.onclick = function() { 
     // do stuff; 
    } 
}); 

或者:

Array.prototype.forEach.call(document.getElementsByClassName('whatever'), function (elem) { 
    elem.addEventListener('click', functionToCallOnClick); 
}); 
+0

我仍然無法得到這個工作,你會介意看看:http://goo.gl/LD4JxV - 點擊任何命令(名單元素)將填充「inputCommand」字段。現在它正在工作,使用document.getElementById,我試圖切換到getElementByClassName,所以我也可以聽其他元素。非常感謝! – Yatko

+0

同時,發現問題'class =「list-unstyled」class =「commandList」'而不是'class =「list-unstyled commandList」',瀏覽器沒有提供任何錯誤,但JS引擎不會理解錯誤。感謝您的時間和答案! – Yatko

相關問題