0

到目前为止,我有以下内容:

<!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”。

有人可以帮忙吗?谢谢!

4

3 回答 3

1
$('.product').change( function() {
  var xkey = $.trim( $(".product option:selected").text() );
  alert(KeysArray[xkey]);
});
于 2013-01-15T17:28:47.657 回答
1

我设法让它在这个jsfiddle 上为你工作。

您需要做的是在这一行的 KeysArray 对象中获取正确的键:

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'; }
于 2013-01-15T17:29:20.830 回答
0

试试这个作为 onchange 回调函数体

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

我希望这有帮助。

于 2013-01-15T17:28:34.700 回答