【问题标题】:Selecting item in list and displaying the selected item's information in another div选择列表中的项目并在另一个 div 中显示所选项目的信息
【发布时间】:2022-01-08 11:15:59
【问题描述】:

我正在从 yelp API 获取 JSON 数据(企业)。我遍历数据以显示业务,并希望在另一个 div 中单击时显示有关业务的更多信息。到目前为止,我有:

        function display_results(businesses) {
            var options = '';
            for (var i = 0; i < businesses.length; i++) {
                options += '<div class="optbtn" value="' + i + '">' + businesses[i].rating.toFixed(1) + "/5\u2606  " + businesses[i].name + '</div>';
            }
            $('#businesses').html(options);


            $('.optbtn').click(function () {
                // index problems
                var index = $(this).val();
                console.log("index: " + index);
                var details = businesses[index];

                var info = '';
                for (key in details) {
                    info += key + ': ' + details[key] + '<br>';
                }
                $('#info').html(info);
            });
        }

        $(function () {
            $("#search_bar").autocomplete({
                source: "/autocomplete",
                minLength: 3,
                select: function (event, ui) {
                    $.ajax({
                        url: "/business_search",
                        type: "GET",
                        data: {
                            term: ui.item.value
                        },
                        success: function (result) {
                            display_results(JSON.parse(result).businesses);
                        }
                    });
                }
            });
        });
    <div class="ui-widget">
        <label for="search_bar">Business Search: </label>
        <input id="search_bar" style="width: 400px;">
    </div>

    <div class="ui-widget">
        Businesses:
        <div id="businesses" style="height: 400px; width: 600px; overflow: auto; white-space: pre;"
            class="ui-widget-content" />
    </div>

    <div class="ui-widget">
        Info:
        <div id="info" style="height: 400px; width: 600px; overflow: auto; white-space: pre;"
            class="ui-widget-content" />
    </div>

我的计划是为每个包含业务的 div 设置一个索引值,然后在单击时使用该值来获取要显示的其余信息。我的问题是我似乎无法使用var index = $(this).val(); 实际获取索引值。我对这一切都很陌生,希望能得到一些关于我哪里出错的指导!

【问题讨论】:

    标签: javascript jquery json


    【解决方案1】:

    您的代码中的主要问题是因为有效的 HTML div 元素不应具有要通过 jQuery 的 val() 方法读取的 value 属性。解决这个问题的简单方法是使用data 属性在 HTML 中存储相关数组实体的索引或 ID。

    另请注意,您可以对逻辑进行一些其他优化以改进它:

    • 使用Array.map()和字符串插值更简洁地构建HTML
    • 对所有动态内容使用单个委托事件处理程序
    • 使用Object.entries() 检索包含给定对象中的键/值对的类数组对象。
    • 将 CSS 规则放在外部 CSS 样式表中,而不是在 HTML 中内联

    话虽如此,这应该适合你:

    jQuery($ => {
      let $businesses = $('#businesses');
      
      // handle click on the business rating
      $businesses.on('click', '.optbtn', e => {
        let index = $(e.currentTarget).data('index');
        let business = $businesses.data('response')[index];    
        $('#info').html(Object.entries(business).map(([k, v]) => `<p>${k}: ${v}</p>`)); 
      });
      
      // update the DOM based on the AJAX response:
      let display_results = businesses => $businesses.html(businesses.map((b, i) => `<div class="optbtn" data-index="${i}">${b.rating.toFixed(1)}/5\u2606 ${b.name}</div>`))
      
      // make your Autocomplete/AJAX call here. 
      // mock AJAX response handler:
      let ajaxResponse = [{ rating: 1.11, name: 'Foo', address: '123 Any Street' },{ rating: 2.22, name: 'Bar', address: '456 Any Town' },{ rating: 4.44, name: 'Fizz', address: '789 Any City' },{ rating: 5.00, name: 'Buzz', address: '123 Any Avenue' }];
    
      display_results(ajaxResponse); // build the UI from the dataset
      $businesses.data('response', ajaxResponse); // store the response for later use
    });
    #search_bar { 
      width: 400px;
    } 
    
    .ui-widget-content {
      width: 600px;
      overflow: auto;
      margin-bottom: 10px;
    }
    
    .ui-widget-content p {
      margin: 0 0 5px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div class="ui-widget">
      <label for="search_bar">Business Search:</label>
      <input id="search_bar" />
    </div>
    <div class="ui-widget">
      Businesses:
      <div id="businesses" class="ui-widget-content"></div>
    </div>
    <div class="ui-widget">
      Info:
      <div id="info" class="ui-widget-content"></div>
    </div>

    【讨论】:

    • 抱歉回复晚了,我要去旅行,没能查到这个。非常感谢,这真的很翔实。关于“对所有动态内容使用单个委托事件处理程序”,这是否意味着我应该尝试将搜索、自动完成和显示结果全部放在一个 jquery() 块中?我对网络开发非常陌生,我很难弄清楚最佳实践是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多