JavaScript根据选定的下拉文本字符串获取二维数组值

JavaScript根据选定的下拉文本字符串获取二维数组值,javascript,jquery,dom,select,Javascript,Jquery,Dom,Select,到目前为止,我有以下几点: <!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html" /> <script src="http://code.jquery.com/jquery-latest.js"></script> <title> Select Value From

到目前为止,我有以下几点:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html" />
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <title>
      Select Value From Array
    </title>
  </head>
  <body>

    <script type="text/javascript">
        var KeysArray = { 
            "Lake":"imageabc.jpg",
            "House":"imagedef.jpg",
            "PC":"imageghi.jpg",
            "Sky":"imagejkl.jpg" 
        } 
        $(function(){
            $('.product').change( function() {
                var xkey = $.trim( $(".product option:selected").text() );
                // alert(xkey);
            }); 
        });
    </script>

    <div>

      <select class="product" title="">
        <option value="">
          -- Select --
        </option>
        <option value="123">
          Lake
        </option>
        <option value="456">
          House
        </option>
        <option value="789">
          PC
        </option>
        <option value="101">
          Sky
        </option>
      </select>

    </div>

  </body>
</html>
一旦我们从下拉列表中选择了一个值,我需要将它的选项文本值与现有的对应数组值进行比较

所以,如果用户选择House,我应该检查是否有一个具有该名称的键,如果是,我需要获取它的数组值。因此,在House示例中,它应该返回imagedef.jpg


有人能帮忙吗?谢谢大家!

尝试将此作为onchange回调函数体

var xkey = $.trim( $(".product option:selected").text() );
alert(KeysArray[xkey] || 'Not found');

我希望这会有所帮助。

我设法让它在JSFIDLE上为您工作

$('.product').change( function() {
  var xkey = $.trim( $(".product option:selected").text() );
  alert(KeysArray[xkey]);
});
您需要做的是在此行的KeyArray对象中获取正确的密钥:

var xkey = KeysArray[ $.trim( $(".product option:selected").text() ) ];
或者,您可以通过两个步骤来提高可读性

var xkey = $.trim( $(".product option:selected").text() );
xkey = KeysArray[xkey];
在继续之前,可能需要检查密钥是否确实存在。我建议在拿到xkey后进行检查

if (typeof xkey !== 'string') { xkey = 'Not found'; }