【问题标题】:Replace d3.select and onchange function with Jquery用 Jquery 替换 d3.select 和 onchange 函数
【发布时间】:2020-05-15 21:22:10
【问题描述】:

我想将此代码转换为 jquery。我对 jQuery 很陌生。在 .data(item) 中,项目是数据集中的一列。在“var item”中,我得到了列的键并将这些键传递给选择按钮。

如果我将此代码转换为 jquery,那么它可以与另一个 JavaScript 库一起使用。

提前致谢。

                <div id="chart1">
                     <select id="selectButton"></select>
                 </div>

      here in the middle, I have bar chart and update function. And in .on(change function{) i call the update function to redraw the chart based on user selection.

            d3.select("#selectButton")
                .selectAll('myOptions')
                .data(item)
                .enter()
                .append('option')
                .text(function (d)
                {
                    return d; }) // text showed in the menu
                .attr("value", function (d)
                {
                    return d; }) // returned value by the button


            // When the button is changed, run the updateChart function
            d3.select("#selectButton").on("change", function(d) {
                // recover the option that has been chosen
                var selectedOption = d3.select(this).property("value")
                // Run the updatechart function upon selection
                update(selectedOption)})```

【问题讨论】:

  • 因为这可能会改变答案,“它可能与另一个 JavaScript 库一起使用是通用的” - 您希望通过使用 jquery 而不是 d3 在可移植性/交叉兼容性方面获得什么收益?
  • 其实我已经把这段代码放在了 Thymeleaf 中,并且我已经从控制器中注入了图表。如果我注入 d3 代码,它可以正常工作,因为我在这里使用 d3.select。如果我注入 High-chart 或 google-chart,则无法更新下拉列表,并且 .on(change 函数将不起作用,因为我使用 d3.select。这就是为什么我更喜欢使用适用于所有基于 javascript 的库的 jquery。
  • 我可以使用以下代码向 ' ); $.each(used_data, function(index, key) { myselect.append( $('').val(key).html(key) ); }); $('# selectButton').append(myselect.html()); });` 现在我想改变.on(改变功能也

标签: javascript jquery d3.js


【解决方案1】:

我改变了它,它可以工作!

$(document).ready(function(){
              var myselect = $('<select>');
              $.each(used_data, function(index, key) {
                  myselect.append( $('<option></option>').val(key).html(key) );
              });
              $('#selectButton').append(myselect.html());

          });

           $('select').on('change' , function () {

              var selectedOption = $("#selectButton").val();

              update(selectedOption)
           })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 2016-08-17
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多