从下拉列表中选择随机值

时间:2014-06-25 17:01:47

标签: javascript

我有这个脚本:

    <script>
    function $(id) {
        return document.getElementById(id);
    }
    function getImage() {

        $('loader').src='/misc/images/loading.gif';
        var url = "http://mousecreator.com/";

        // outfit
        var head = "&head="+$('head').value;
        var ears = "&ears="+$('ears').value;
        var eyes = "&eyes="+$('eyes').value;
        var mouth = "&mouth="+$('mouth').value;
        var neck = "&neck="+$('neck').value;
        var ears = "&ears="+$('ears').value;
        var hair = "&hair="+$('hair').value;
        var fur = "&fur="+$('fur').value;
        var tail = "&tail="+$('tail').value;


        // sham
        if(document.sh.sham.checked)
            var sham = "&sham=1";
        else
            var sham = "";

        //alert(document.sh.sham.checked);


        var murl = url +"mouse.php?" + head + ears + eyes + mouth + neck + ears + hair + fur + tail + sham;

        // set the preview image and text box
        $('prem').src=murl;
    }

    function remLoad() {
        $('loader').src="";
    }</script>

            <select id="head">
        <option value="235">Value 1</option>
        <option value="324">Value 2</option>
    ...
    ...
<button onclick="getImage()">Generate</button>

有没有办法在单击Generate按钮的同时使按钮从所有下拉列表中随机选择id?每个id(头部,耳朵,眼睛等都有它自己的下载列表)

提前致谢!

1 个答案:

答案 0 :(得分:1)

function randomItemFrom(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

function randomOptionFrom(select) {
    return randomItemFrom(select.options);
}

var randomEye = randomOptionFrom($('#eyes')[0]).value;

您还可以使randomOptionFrom函数接受jQuery对象或选择器。

function randomOptionFrom(select) {
    return randomItemFrom($(select)[0].options);
}

然后你可以这样称呼它:

randomOptionFrom($('#eyes')).value;

randomOptionFrom('#eyes').value;