jQuery动态设置id

时间:2012-07-06 01:58:43

标签: jquery

我正在尝试通过jQuery动态设置div id。昨天,似乎代码工作正常,但今天,它正在抱怨。

有问题的循环是:

    socket.on('nicknames', function (nicknames) {
    $('#nicknames').empty().append($('<span>Online: </span>'));
      for (var i in nicknames) {
    $('#nicknames').append($('<div class="chatNickname" id="' + nicknames[i] + '">').text(nicknames[i]));
      }
    });

问题是,当我动态设置ID时,用户列表只有一个 - 本地用户。如果我将ID设置为静态的,它可以工作,并且整个用户列表都可见。

我认为这是一个语法问题,但是从这个页面(http://www.dynamicdrive.com/forums/showthread.php?t=36730),我认为我做得对。

感谢您的帮助!

整个代码是:

<script src="http://<?php print $_SERVER['SERVER_ADDR'] ?>:8080/socket.io/socket.io.js"></script>
<script>
  (function($){
    var myNick = 'me';
    var newlyJoined = true;
    var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8080');

    socket.on('connect', function () {
      $('#chat').addClass('connected');
    });

    socket.on('announcement', function (msg) {
      $('#lines').append($('<p>').append($('<em>').text(msg)));
    });

        socket.on('nicknames', function (nicknames) {
        $('#nicknames').empty().append($('<span>Online: </span>'));
          for (var i in nicknames) {
        $('#nicknames').append($('<div class="chatNickname" id="' + nicknames[i] + '">').text(nicknames[i]));
          }
        });

    socket.on('user message', message);
    socket.on('reconnect', function () {
      $('#lines').remove();
      message('System', 'Reconnected to the server');
    });

    socket.on('reconnecting', function () {
      message('System', 'Attempting to re-connect to the server');
    });

    socket.on('error', function (e) {
      message('System', e ? e : 'A unknown error occurred');
    });

    socket.on('chat log', function(chatlog) {
      if (newlyJoined) {
    var i = 0;
    for (stamp in chatlog) {
      if (chatlog[stamp].type == 'user message') {
    var ts   = tstamp(stamp);
    var nick = chatlog[stamp].nick
    var msg  = chatlog[stamp].msg
    message(ts, nick, msg);
    i++;
      }
    }
    if (i > 0) {
      $('#lines').append($('<hr>')).append($('<small style="text-align:center; display:block; color: #888;">').text('Chat messages posted within the past half hour appear above this line.')).append($('<hr>'));
      $('#lines').get(0).scrollTop = 10000000;       
    }
    newlyJoined = false;
      }
    });

    function message (msg_time, from, msg) {
      $('#lines').append($('<p>').append($('<small>').text(msg_time)).append($('<b>').text(from), linkify(msg)));
    }

    function linkify(inputText) {
      //URLs starting with http://, https://, or ftp://
      var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
      var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

      //URLs starting with www. (without // before it, or it'd re-link the ones done above)
      var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
      var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

      //Change email addresses to mailto:: links
      var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
      var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

      return replacedText
    }

    function tstamp(stamp) {
      var currentTime = new Date(); 
      if (typeof stamp != 'undefined') {
    currentTime.setTime(stamp);
      }
      var days = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat');
      var day = currentTime.getDay();
      var hours = currentTime.getHours();
      var minutes = currentTime.getMinutes();
      if (minutes < 10) {
    minutes = "0" + minutes;
      }
      if (hours > 11) {
    var ap = 'p';
      }
      else {
    var ap = 'a';
      }
      if (hours > 12) {
    hours = hours - 12;
      }
      return "["+ days[day] + " " + hours + ":" + minutes + ap + "m] ";
    }

    $(document).ready(function() {

      $('#nicknames').on('click', '.chatNickname', function(){ 
   alert("hello");
});

      $('input#message').focus(function() {
    if ($(this).val() == 'Type your chat messages here...') {
      $(this).val('');
    }
      });

      $('input#show-timestamps').click(function() {
    if ($(this).is(':checked')) {
      $('#messages p small').show();
    }
    else {
      $('#messages p small').hide();
    }
      })

      socket.emit('nickname', '<?php print $username ?>', function (nick) {
    if (nick != 'me') {
      myNick = nick;
      socket.emit('get log');          
      return $('#chat').addClass('nickname-set');
    }
      });

      $('#send-message').submit(function () {
    message(tstamp(), myNick, $('#message').val());
    socket.emit('user message', $('#message').val());
    clear();
    $('#lines').get(0).scrollTop = 10000000;
    return false;
      });

      function clear () {
    $('#message').val('').focus();
      };

    });
  })(jQuery);
</script>
<div id="chat">
  <div id="messages">
    <div id="nicknames">
    </div>
    <div id="lines">
    </div>
  </div>
  <form id="send-message" autocomplete="off">
    <input id="message" type="text" value="Type your chat messages here..." autocomplete="off" />
    <button>Send</button>
  </form>
</div>
<small><input id="show-timestamps" type="checkbox" checked="checked" /> Show timestamps</small>a

2 个答案:

答案 0 :(得分:0)

很多问题,据我所知,主要是你用for...in迭代一个数组。您必须使用常规for循环执行此操作。此外,append()方法接受html字符串,因此您将对象包装在jQuery中两次。然后,您忘记关闭标记中的div,并且您不需要使用text()只需将其添加到html中。最后,为了获得最佳性能,请将所有标记缓存到变量中,并最后添加所有内容,以避免多次DOM重排,这是非常昂贵的。

socket.on('nicknames', function (nicknames) {
  var divs = []
  for (var i = 0, l = nicknames.length; i < l; i++)
    divs.push(
      '<div class="chatNickname" id="'+ nicknames[i] +'">'+
        nicknames[i] +
      '</div>'
    )
  $('#nicknames')
    .empty()
    .append(
      '<span>Online: </span>'+
      divs.join('')
    )
})

nicknames在哪里宣布? JavaScript没有变量引用,除非你传入一个对象,在这种情况下它似乎是一个数组,所以我猜你可能不需要nicknames参数......

答案 1 :(得分:0)

请尝试以下方法:

socket.on('nicknames', function (nicknames) {
    $('#nicknames').empty().append($('<span>Online:</span>'));
    for (var i in nicknames) {
        var attrs = {
            'class': 'chatNickname',
            'id': nicknames[i],
            'text': nicknames[i]
        };
        $('#nicknames').append($('<div>',attrs));
    }
});

<强> demo