开发者

Not storing in the array

On my page I have:

        function grabProfiles(searchstring) {
            $.post('newsletter.php?mode=grab', { search: searchstring }, function(data) {
                $('#newsletter_receivers').html(data);
            });
        }
        $('#newsletter_searchprofiles').bind('keyup', function() {
            var searchstring = this.value;
            grabProfiles(searchstring);
        });
        $(document).ready(function() {
            grabProfiles('');
        });

This outputs the result in div element #newsletter_receivers. The result looks something like this:

<div class="receiver">
 Peter
</div>
<div class="receiver">
 Maria
</div>
<script>
$(".receiver").click(function () {
$(this).toggleClass("newsletter_receiver_highlight");
});
</script>

So when you cl开发者_Go百科ick on one of the receivers, they will be highlighted. This works fine.

Now I would like to put the receiver's id attribute value (the highlighteds id value) in an array. And then alert this arrays value when you click on a submit button that exists under the #newsletters_receivers. (not in the ?mode=grab where all the .receiver elements is)

I did like this:

         $('#newsletter_send').click(function(){
                 alert($('div.newsletter_receiver_highlight').length+' Selected');
                var arr = [];
                $('div.newsletter_receiver_highlight').each(function(){
                    arr.push(this.id);
                });
                alert(arr);
         });

This gives me two alerts. The one is right, it gives me the numbers of how many is highlighted. The second alert which should give me the values, is empty!

This worked previously when I did not made a ajax request to output the receiver elements. And i think it is empty because first time the page doesnt contain anything in #newsletters_receivers , until it makes the ajax request. But how can it tell the right length then?

How can i fix/ make a solution for this in order to work?

// Conclusion question:

Why is each() not live? and alternatives than this method?

example:

$('div.newsletter_receiver_highlight').each(function(){
    arr.push(this.id);
});
alert(arr);

this stores value for all the CURRENT elements with the class newsletter_receiver_highlight

If i append a div element with class newsletter_receiver_highlight later from an request response, it wont store to the array


If something doesn't work in first place always try a different approach. I would use map to get the array of ids.

var arr = $('div.newsletter_receiver_highlight').map( function() { return this.id; } ).get();

This comes instead of .each()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜