开发者

Selecting a div in jQuery & appending to the DOM

        var activeMsg=[];       // Active Users
        var noactiveMsg=[];     // Non-Active Users with a Pending Message
        var noactiveNomsg=[];       // Non-Active Users without a Pending Message

        $('div.chatmember').each(function() {
            currentMember=$(this);

            if($(this).children().children('div').hasClass('chatactivestatus_online')) {
                alert('online');
                activeMsg.push(currentMember);
            }
            if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
                alert('offline');
                noactiveMsg.push(currentMember);
            }               
        });

        $.each(noactiveMsg, function(i, e){
             $('#chatCenterMembers').append(e.html());
         })

The above code is quering DOM structure that looks like this:

 <div id="chatCenterMembers">
   <div class="chatmember">
      <a class="ststusTitle">
         <div class="chatactivestatus_online"></div>

it all works except for currentMember=$(this开发者_如何学JAVA); I believe this should hold <div class="chatmember">

when I do the append at the end of the code above it doesn't add <div class="chatmember"> back into the dom. It adds its children elements only.


So you issue is this line here:

$('#chatCenterMembers').append(e.html());

and more specifically: e.html()

Accourding to the jQuery spec for .html():

Get the HTML contents of the first element in the set of matched elements.

which means that .html() returns the child contents of the selection, not the selection itself.

What you want to do, is just use .append(), this will append the entire selected div and not just it's children


I think you just raced ahead a little bit. Using your js, $(this) will refer to your inner div. $(this).parent() will refer to the outer one.


some html

<div id="chatCenterMembers">
   <div id="adam" class="chatmember">
       hello!
    </div>
</div>

the js

$(function(){
    $("div.chatmember").each(function(){

        // current member is now div#adam
        var currentMember = $(this);

        currentMember.css('border', '5px solid blue');

        // parent of currentMember references div#chatCenterMembers
        currentMember.parent().css('border', '5px solid red');

    });
});

see it working here on jsFiddle


Try:

$('div.chatmember').each(function(domEle){
    currentMember=$(domEle);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜