【问题标题】:JavaScript Get two dimensional array value based on selected drop down text stringJavaScript 根据选定的下拉文本字符串获取二维数组值
【发布时间】:2013-01-16 01:29:20
【问题描述】:

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

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

有人可以帮忙吗?谢谢!

【问题讨论】:

    标签: javascript jquery dom select


    【解决方案1】:

    我设法使它在 this 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'; }
    

    【讨论】:

      【解决方案2】:
      $('.product').change( function() {
        var xkey = $.trim( $(".product option:selected").text() );
        alert(KeysArray[xkey]);
      });
      

      【讨论】:

        【解决方案3】:

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

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

        我希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多