いちにち
いちにち

Reputation: 417

Calling a method of a global object from a function

I found out how to solve the problem but I could not understand what the problem was although, I know why it is working now.

Here is the code that works:

function onReceive(json) {
  for (var i = 0; i < json.length; i++) {
    var m = $("<p/>", {
      "class": "message",
      html: json[i].message
    });

    $("#messages").append(m);
  }
}

I quote from here:

var carName = " Volvo";

// code here can use carName
function myFunction() {
  // code here can use carName
}

My question is, why wouldn't this work?

messages = $("#messages");

function onReceive(json) {
  for (var i = 0; i < json.length; i++) {
    var m = $("<p/>", {
      "class": "message",
      html: json[i].message
    });

    messages.append(m);
  }
}

Upvotes: 0

Views: 57

Answers (2)

ertrzyiks
ertrzyiks

Reputation: 386

You need to get element when it is part of page already.

You could wrap $ call with document ready callback, like this:

$(document).ready(function () {
    messages = $("#messages");
});

Otherwise selector return empty collection (no element with id messages found).

Such wrapper is not required in event handlers, because event callbacks are always called after document is ready.

Upvotes: 2

Tarun
Tarun

Reputation: 1898

I guess you are using messages = $("#messages"); before DOM ready. So at that time your javaScript not able to get $("#messages") and you are using onReceive() function after DOM load so it's working inside your function.

Upvotes: 3

Related Questions