JQuery 选择器无法从外部 js 文件工作

JQuery selector not working from external js file

  1. 我正在使用库 jquery.peity.min.js 并先加载它。

  2. 然后我有myscript.js,它使用上面库中的函数如下。

    $(".donut-mult").peity("donut", {
      width: 82,height:82,
      innerRadius:35,
      fill: ["#2ac7d7", "#fff"]
    })  
    

这个myscript.js是在jquery.peity.min.js之后加载的。

  1. 现在我 ajax 调用 sample.jsp

  2. sample.jsp 跨度如下

    <span class="donut-mult">5/5</span>
    

myscript.js 中的 javascript 函数未绑定到此范围 class,因此我无法看到预期的可视化效果。

有什么建议吗?

如果您在通过 ajax 加载内容之前进行了 jquery 选择,它将不起作用,因为它们尚不存在于文档中。在调用任何使用这些 html 元素的函数之前,您需要先加载内容。

在您的 myscript.js

中使用此代码
$(document).ready(function() {
    // The container where you will load the content of sample.jsp
    var $container = $('#donut-container'); 

    // Load via ajax
    $.ajax({
        url: 'sample.jsp',
        type: 'GET',
        success: function(data) {
            // load sample.jsp content to the container
            $container.html(data); 

            // process the spans with class="donut-mult" loaded in the container
            // you can also use $('#donut-container .donut-mult').peity(...) 
            // instead of `$container.find`
            $container.find('.donut-mult').peity("donut", {
                width: 82,height:82,
                innerRadius:35,
                fill: ["#2ac7d7", "#fff"]
            })  
        }
    })
});