javascript - 如何在同一个html中多次调用JS函数

标签 javascript jquery html

这是我用于在两个 block 中调用相同 js 函数的代码(在两个 div 标记中)。第二个标签 (div id="frame4") 的答案也打印在第一个标签 (div id="frame3") 中。我想单独打印它们。我该怎么做?

 <div id="frame3">

     <! ----pieChart ----- !>
     <h5><i>Code Coverage</i></h5> 
      <div id="pieChart"></div>
      <script type="text/javascript">


       dsPieChart(<%=coverage %>); 
      </script>

  </div>

  <!test_density !>
   <div id="frame3">
     <div id="pieChart"></div>
    <script type="text/javascript">


     dsPieChart(<%=density %>); 
      </script>
   </div>

函数代码

  function dsPieChart(x){
     var   formatAsPercentage = d3.format("%") ;
    var dataset = [
        {category: "", measure:x },
        {category: "", measure:(100-x)},

    ]
    ;

    var   width = 100,
         height = 100,
         outerRadius = Math.min(width, height) / 2,
         innerRadius = outerRadius * .9,
         // for animation
         innerRadiusFinal = outerRadius * .8,
         innerRadiusFinal3 = outerRadius* .7,
         color = d3.scale.category20b()   //builtin range of colors
         ;

    var vis = d3.select("#pieChart")
         .append("svg:svg")              //create the SVG element inside the <body>
         .data([dataset])                   //associate our data with the document
             .attr("width", width)           //set the width and height of our visualization (these will be attributes of the <svg> tag
             .attr("height", height)
            .append("svg:g")                //make a group to hold our pie chart
             .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")")    //move the center of the pie chart from 0, 0 to radius, radius
          ;

    var arc = d3.svg.arc()              //this will create <path> elements for us using arc data
            .outerRadius(outerRadius).innerRadius(innerRadius);

     // for animation
    var arcFinal = d3.svg.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius);
    var arcFinal3 = d3.svg.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius);

     var pie = d3.layout.pie()           //this will create arc data for us given a list of values
          .value(function(d) { return d.measure; });    //we must tell it out to access the value of each element in our data array

     var arcs = vis.selectAll("g.slice")     //this selects all <g> elements with class slice (there aren't any yet)
          .data(pie)                          //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties)
          .enter()                            //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
              .append("svg:g")                //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
                 .attr("class", "slice")    //allow us to style things in the slices (like text)
                 .on("mouseover", mouseover)
              .on("mouseout", mouseout)
              .on("click", up)
              ;

          arcs.append("svg:path")
                 .attr("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
                 .attr("d", arc)     //this creates the actual SVG path using the associated data (pie) with the arc drawing function
            .append("svg:title") //mouseover title showing the figures
          //   .text(function(d) { return d.data.category + ": " + d.data.measure ; });
           .text(function(d) { return  d.data.measure ; });

          d3.selectAll("g.slice").selectAll("path").transition()
            .duration(750)
            .delay(10)
            .attr("d", arcFinal )
            ;
      // Add a label to the larger arcs, translated to the arc centroid and rotated.

      arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; })
          .append("svg:text")
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .attr("transform", function(d) { return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")"; })
          .text(function(d) { return d.data.category; })
          ;
       // Computes the label angle of an arc, converting from radians to degrees.
      function angle(d) {
          var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
          return a > 90 ? a - 180 : a;
      }
      // Pie chart title
      vis.append("svg:text")
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .text(x +"%")
          .attr("class","title")
          ;

    function mouseover() {
      d3.select(this).select("path").transition()
          .duration(750)
                .attr("d", arcFinal3)
                ;
    }

    function mouseout() {
      d3.select(this).select("path").transition()
          .duration(750)
                //.attr("stroke","blue")
                //.attr("stroke-width", 1.5)
                .attr("d", arcFinal)
                ;
    }

    function up(d, i) {
          /* update bar chart when user selects piece of the pie chart */
          //updateBarChart(dataset[i].category);
          updateBarChart(d.data.category, color(i));
          updateLineChart(d.data.category, color(i));

    }
  }

最佳答案

更改函数以传递元素 ID 的第二个参数。

function dsPieChart(x, selectorId){

更改硬代码选择器:

var vis = d3.select("#pieChart");

var vis = d3.select("#" + selectorId);  

然后,当您调用该函数时,还要在第二个参数中标识 id 选择器。请注意,根据定义,元素 ID 在页面中必须是唯一的:

<div id="pieChart-1"></div>
 <script type="text/javascript">
   dsPieChart(<%=coverage %>, 'pieChart-1'); 
  </script>
</div>

<div id="pieChart-2"></div>
 <script type="text/javascript">
   dsPieChart(<%=density %>, 'pieChart-2'); 
  </script>
</div>

关于javascript - 如何在同一个html中多次调用JS函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32170829/

相关文章:

javascript - 正则表达式将 XML 转换为 JSON

javascript - 定时鼠标悬停后激活弹出菜单,然后在鼠标移开时取消激活

javascript - 根据每月几周的间隔过滤和映射数据

html - 使用 CSS 重现包含 div 效果的图像

javascript - Angular 2 组合表单验证

javascript - 如何使用纯 javascript 在任何网站中动态包含 jQuery

jquery - 如何使用 jQuery 让我的图像淡入淡出

javascript - jQuery 显示/隐藏不起作用

javascript - 使用 Ajax 获取随机维基百科摘录

javascript - 我正在使用 OWASP ESAPI encodeForHTMLAttribute 但是符号显示为它们的 html 实体编号而不是符号