简体   繁体   English

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

[英]JQuery selector not working from external js file

  1. I am using a library jquery.peity.min.js and loading it first. 我正在使用库jquery.peity.min.js并首先加载它。

  2. Then I have myscript.js which uses the function in above library as follows. 然后我有myscript.js ,它使用上述库中的函数,如下所示。

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

This myscript.js is loaded after jquery.peity.min.js . myscript.jsjquery.peity.min.js之后jquery.peity.min.js

  1. Now I make ajax call to sample.jsp . 现在,我对sample.jsp进行ajax调用。

  2. sample.jsp has a span as follows sample.jsp的跨度如下

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

The javascript function in myscript.js is not getting bound to this span class and hence I cannot see the expected visualization. myscript.js的javascript函数未绑定到此span类,因此无法看到预期的可视化效果。

Any suggestions ? 有什么建议么 ?

If you make a jquery selection before loading contents via ajax it will not work because they don't yet exist in the document. 如果您在通过ajax加载内容之前进行了jquery选择,那么它将不起作用,因为它们尚不存在于文档中。 You need to load the content first before calling any functions that uses those html elements. 您需要先加载内容,然后再调用使用这些html元素的任何函数。

Use this code in your myscript.js 在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"]
            })  
        }
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM