从列表菜单中获取选择索引并将其放入函数中

Get selectedIndex from list menu and put it in function

本文关键字:函数 索引 列表 菜单 获取 选择      更新时间:2023-09-26

在这里,我有一个代码function findPlaces,用于搜索框中放置的对象等。

function findPlaces(boxes,searchIndex) {
   var request = {
       bounds: boxes[searchIndex],
       types: ["museum"]
   };

这工作很好,但现在...

现在我想用列表/菜单中的值更改此类型,所以我这样做:

//JS CODE
function findPlaces(boxes,searchIndex) {
   var request = {
       bounds: boxes[searchIndex],
       types: document.getElementById("select").selectedIndex
   };

和 HTML 代码:

<label for="select"></label>
        <select name="select" id="select">
          <option>restaurant</option>
          <option>bar</option>
          <option>museum</option>
          <option>gas_station</option>
        </select>

并且此代码不会从列表/菜单中获取值并使用新值运行函数

我该如何解决这个问题?

试试这个jQuery代码,一旦你选择了元素,就会把索引发送到findPlaces,这会提醒它:

$("#select").change(function(){
        var values= $('#select option').map(function(){
                        return this.value;
                    }).get();
        var index=jQuery.inArray($(this).val(), values);
      
        findPlaces(boxes, index);//send index to your function
    });
 
 

在这里演示

您可以像这样检索选择值:

var boxes = ['a', 'b', 'c'];
function findPlaces(boxes, searchIndex) {
   var select = document.getElementById("select")
   return {
       bounds: boxes[searchIndex],
       types: select.options[select.selectedIndex].value
   };
}
document.getElementById("select").onclick = function() {
    var r = findPlaces(boxes, 2);
    alert(r.types);
};

此处的示例:http://jsfiddle.net/zaCZw/