【问题标题】:JQuery selector not working from external js fileJQuery 选择器在外部 js 文件中不起作用
【发布时间】:2015-03-22 01:56:01
【问题描述】:
  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. 现在我对sample.jsp进行ajax调用。

  2. sample.jsp 的跨度如下

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

myscript.js 中的 javascript 函数没有绑定到这个 span 类,因此我看不到预期的可视化效果。

有什么建议吗?

【问题讨论】:

  • 委托事件处理程序!
  • 这里确保你的脚本$(".donut-mult").peity("donut", { width: 82,height:82,innerRadius:35,fill: ["#2ac7d7", "#fff"] })sample.jsp被加载后执行
  • @adeneo 好像是插件初始化...
  • @ArunPJohny - 哦,是的,我刚刚读到 “ajax ... 不适用于新元素”

标签: javascript jquery html ajax jsp


【解决方案1】:

如果您在通过 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"]
            })  
        }
    })
});

【讨论】:

  • 我已经尝试过了,但我不知道为什么,但它不起作用
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多