我无法将下拉列表的默认值设置为最后一项

I cannot set the default of a drop downlist to the last item

本文关键字:最后 一项 设置 下拉列表 默认值      更新时间:2024-05-14

我无法将下拉列表的默认值设置为最后一项。如果下拉列表中有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循环之外。

再说一遍,可能不值得,但你的决定。