开发者

How to run javascript on an ajax output?

开发者 https://www.devze.com 2022-12-27 06:04 出处:网络
I am using jquery-ui tabs and ajax to load the content of the tabs. Here is my javascript: $(document).ready(function() {

I am using jquery-ui tabs and ajax to load the content of the tabs. Here is my javascript:

 $(document).ready(function() {
     $("#tabs").tabs({ fx: { opacity: 'toggle' } });
     $('.hd_item').hover(function() {
     //Display the caption
         $(this).find('span.hd_caption').stop(false,true).fadeIn(600);
     },
     function() {
     //Hide the caption
         $(this).find('span.hd_caption').stop(false,true).fadeOut(400);
 开发者_JAVA百科    });
 });

When the user clicks on the tab is will load the content.php via ajax. The output of the ajax is:

 <li class="hd_item">
      <img title="Backyard Brawl" alt="Backyard Brawl" src="games/normal_icons/1844.png" id="hd_icon">
           <span class="hd_caption">
                <h1>Backyard Brawl</h1>
                <p id="hd_description">In this game you pick a player and beat each other up with ...</p>
                <p id="hd_stat">Added: <br>2009-12-14</p><a href="/dirtpilegames/index.php?ground=games&amp;action=play&amp;dig=backyard-brawl">PLAY</a>
           </span>
 </li>

The problem that I am having is the javascript is not working on the ajax output. How to I get it to work on it?


If I'm not mistaken it's because you're binding the hover event to items that don't exist yet (since the AJAX call takes some non-zero amount of time to execute). You may want to try using:

jQuery's live() function

Instead of the .hover() function to make your bind.


you can try putting the hover function inside your ajax success function


It's because the hd_items you're adding weren't found when the ready() function was called so they don't have hover event functions. Take that snippet out of the ready() and call it after you load the ajax response.


When you ask jQuery to, for example, find all elements with the class .hd_item on the page, you are only asking jQuery about the elements of the current document. If you add more elements to the document jQuery has no inkling to rerun your past commands. The solution is to, of course, tell jQuery to rerun those past commands.

$(document).ready(function() {
     $("#tabs").tabs({ fx: { opacity: 'toggle' } });
     registerTabContent();
});

// This function mocks whatever loads your Ajax content
function loadSomeAjaxyStuff() {
    loadMyTab();
    // After we load the content, we rerun the code to pick up the new
    // (well, it gets the old ones as well) elements we've added.
    registerTabContent();
}

function registerTabContent() {
    $('.hd_item').hover(function() {
     //Display the caption
         $(this).find('span.hd_caption').stop(false,true).fadeIn(600);
     },
     function() {
     //Hide the caption
         $(this).find('span.hd_caption').stop(false,true).fadeOut(400);
     });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号