admin管理员组

文章数量:1323150

I need to learn how to initialize scripts. I have google it but dont dont really understand it.

Right now I have a toggle-script that is in a div, that entire div gets loaded in to another page. The toggle scripts work, but not when its loaded in.

$(".class").click(function () {
$(this).toggleClass("add_class");
});

If somebody have time, can you explain to me how to initialize this script?

Thanks.

I need to learn how to initialize scripts. I have google it but dont dont really understand it.

Right now I have a toggle-script that is in a div, that entire div gets loaded in to another page. The toggle scripts work, but not when its loaded in.

$(".class").click(function () {
$(this).toggleClass("add_class");
});

If somebody have time, can you explain to me how to initialize this script?

Thanks.

Share edited Dec 21, 2012 at 13:44 Dark Falcon 44.2k5 gold badges90 silver badges102 bronze badges asked Dec 21, 2012 at 13:42 user1905754user1905754 2
  • Have you considered using .live("click", function()...) instead of .click() ? – Thomas Commented Dec 21, 2012 at 13:44
  • @Thomas live() is deprecated. – epascarello Commented Dec 21, 2012 at 13:45
Add a ment  | 

4 Answers 4

Reset to default 5

You should put this script inside a document.ready call.

Eg.

$(document).ready(function() {
    //Put your code here
});

If I misunderstood your question and what you actually mean is:

How do you execute the script after you load it in through an AJAX call. Then see this question: executing script after jQuery Ajax Call

Are you calling it after the elements are loaded on the page?

You should be using on() with jQuery 1.7+

$(document).on("click", ".class", function () {
    $(this).toggleClass("add_class");
});

If you want to keep your syntax, you would have to do it either after the elements are rendered, or do it on document.ready.

I figure you're using jquery.ajax to fetch the div?

If so, you should be able to add the listeners in the success-function of the jquery.ajax call:

$('#result').load('ajax/test.html', function() {
  $("#result .class").click(function () {
    $(this).toggleClass("add_class");
  });
});

simple and best

$(function(){
    //your code here...
    $(".class").click(function () {
       $(this).toggleClass("add_class");
    });
});

本文标签: javascriptInitialize scriptStack Overflow