开发者

jquery each function for dynamically elements

开发者 https://www.devze.com 2022-12-19 08:45 出处:网络
I am dynamically adding a class to my code using Jquery\'s .attr(\'class\', \'sh开发者_JS百科ow\'). But when I use .each() function like this:

I am dynamically adding a class to my code using Jquery's .attr('class', 'sh开发者_JS百科ow'). But when I use .each() function like this:

$('.show a').each(function() {
    alert(0);
});

it doesen't work.

I works when I added the 'show' class manually.

How can I do this dynamically?


Use "addClass" instead of trying to set the class via "attr()".


I assume you mean that you're adding a class to an existing element. If so it may work better if you used:

$('.myElement').addClass('show');

If you need to add an element to the dom, that's a completely different matter.

EDIT:

To address the new info you gave, there are two things to change:

First, use addClass:

$('#existing div:first').show().addClass('show');

Second, you forgot the . before 'show' for your each. It should be ('.show a'):

            $('.show a').each(function() {
                alert(0);
            });


I have existing element div.

$('#somewhere').click(function() {                  

                $('#existing div:first').show().attr('class', 'show');

                $('show a').each(function() {
                    alert(0);
                });
});     

My code: <div id="existing"> <div> <a href="#">a1</a> <a href="#">a2</a </div> <div> <a href="#">b1</a> <a href="#">b2</a> </div>

I tried .addClass and .attr...

0

精彩评论

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