我无法将下拉列表的默认值设置为最后一项
I cannot set the default of a drop downlist to the last item
我无法将下拉列表的默认值设置为最后一项。如果下拉列表中有3个项目,我希望第三个项目是下拉列表的默认项目。html,其中填充下拉列表。
<div class='select'>
<select id='videoSource'></select>
</div>
javascript打开相机并在电脑上显示可导航的相机。有人能帮我吗?
<script type="text/javascript">
var videoElement = document.querySelector("video");
var videoSelect = document.querySelector("select#videoSource");
var startButton = document.querySelector("button#start");
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
function gotSources(sourceInfos) {
for (var i = 0; i != sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
var option = document.createElement("option");
option.value = sourceInfo.id;
if (sourceInfo.kind === 'video') {
option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.'n'nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources);
}
function successCallback(stream) {
window.stream = stream; // make stream available to console
videoElement.src = window.URL.createObjectURL(stream);
videoElement.play();
}
function errorCallback(error) {
console.log("navigator.getUserMedia error: ", error);
}
function start() {
if (!!window.stream) {
videoElement.src = null;
window.stream.stop();
}
var videoSource = videoSelect.value;
var constraints = {
video: {
optional: [{ sourceId: videoSource}]
}
};
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
videoSelect.onchange = start;
start();
对于最后一个选项,在For循环中将selected
属性设置为true
。
if( i == sourceInfos.length - 1 ) {
option.selected = true;
}
最简单的解决方案是在gotSources函数中添加新选项后,添加
videoSelect.value = sourceInfo.id;
所以它会读取
if (sourceInfo.kind === 'video') {
option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
videoSelect.value = sourceInfo.id; //update the value to the last element
} else {
console.log('Some other kind of source: ', sourceInfo);
}
这将为每添加一个新选项设置它(不是最"高效"的解决方案,但肯定不会降低性能)。如果您想只发出一次value set命令,则需要存储最后添加的选项,并将其设置在for循环之外。
再说一遍,可能不值得,但你的决定。
相关文章:
- 如何从对象数组中获取最后一项
- 为什么只有最后一项显示,而不是全部显示
- 删除最后一项jquery
- 为什么我的“for”循环只获取 html 中的最后一项
- 我无法将下拉列表的默认值设置为最后一项
- 流星批量插入仅插入最后一项
- 我怎么能知道元素是最后一项
- 如何删除WinJS组绑定列表的最后一项
- 使用handlers.js模板以数组中的最后一项为条件
- empty().append()追加循环中的最后一项
- jQuery只附加最后一项
- 将属性添加到 for 循环中的最后一项
- 如何按排序键顺序获取对象中的最后一项
- for 循环中的 addEventListener 始终添加到最后一项
- 从数组中删除最后一项
- CasperJS只从我的for循环中多次发布最后一项
- 在 JavaScript 中处理数组中的最后一项
- 胡子.js带有数组,最后一项除外
- 通过jQuery在最后一项之后插入
- JavaScript for 循环只返回数组中的最后一项