문제

So i searched around on the internet and didn't really understand how this works. I have a div element on my page that loads the leaderboard for my game dynamically. The idea was so that when you click on a player's name, the div fills with their personal stats, replacing the old one. It was meant so the page doesnt need to refresh. The url class never changes, and the id always changes depending on the user's name.

In the code the link is generated like this:

<a class="ulink" id="'.$user.'" href="#">'.$user.'</a>

and my jquery like this:

$(".ulink").on('click', function (event) {
        alert("hi");
        event.preventDefault();
});

When i click on the player's name it loads fine but when i click let's say a different skill to load the div with the main table again, and try to click the player's name again, it stops working ???

I've literally spent days on this part of my leaderboard script and its being a complete pain in the butt.

How do i make it so that when the div is reloaded that the links will continue to send the alert message? After i replace the DIV element they no longer work. I looked it up on google but could not come down with a solution.

Thanks in advance.

도움이 되었습니까?

해결책

Since you are dynamically creating the elements use the following code:

   $("body").on("click", ".ulink", function (event) {
            alert("hi");
            event.preventDefault();
     });

다른 팁

$(".ulink").on only does something to the .ulinks that are currently there. If you create new ones later, they won't have the event attached. Either call your on code again or use delegate.

If you bind your event listener to the document and use jQuery on() then the event will be added to new and existing elements. Try this:

$(document).on('click', '.ulink', function (event) {
        alert("hi");
        event.preventDefault();
});

For more info check out the jQuery documentation: http://api.jquery.com/on/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top