在div标记中包装.addEventListener

时间:2015-02-04 12:56:20

标签: javascript jquery html css json

我是js的新手,我需要帮助在行之间使用html。

我有这个活动:

 eventSource.addEventListener('Uptime', function(e) {
        var parsedData = JSON.parse(e.data);
        var tempSpan = document.getElementById("uptime");
        var tsSpan   = document.getElementById("tstamp");
        tempSpan.innerHTML = parsedData.data;
        tempSpan.style.fontSize = "28px";
        tsSpan.innerHTML = "At timestamp " + parsedData.published_at;
        tsSpan.style.fontSize = "9px";
    }, false);

它会从我的Spark Core中侦听事件,并以状态更新我的网站。

我想要的是在我的div中显示的状态。

<div id="on"> </div>

这可能吗?

完整代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Spark.aspx.cs"     Inherits="Spark" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="/Content/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
     <span id="uptime"></span><br>
    <span id="tstamp"></span>

   <br><br>
<button onclick="start()">Connect</button>

<script type="text/javascript">
    function start() {


    document.getElementById("uptime").innerHTML = "Waiting for data...";
    var deviceID = "";
    var accessToken = "";
    var eventSource = new EventSource("https://api.spark.io/v1/devices/" + deviceID + "/events/?access_token=" + accessToken);

    eventSource.addEventListener('open', function(e) {
        console.log("Opened!"); },false);

    eventSource.addEventListener('error', function(e) {
        console.log("Errored!"); },false);

    <!--THIS IS THE METHOD I WANT INSIDE THE DIV-->
    eventSource.addEventListener('Uptime', function(e) {
        var parsedData = JSON.parse(e.data);
        var tempSpan = document.getElementById("uptime");
        var tsSpan   = document.getElementById("tstamp");
        tempSpan.innerHTML = parsedData.data;
        tempSpan.style.fontSize = "28px";
        tsSpan.innerHTML = "At timestamp " + parsedData.published_at;
        tsSpan.style.fontSize = "9px";
        var div = document.createElement("div")
        div.innerHTML = parsedData.status;

        document.body.appendChild(div);

        document.getElementById("on").innerHTML = parsedData.status;
    }, false);

}
</script>

这是截图。 http://imgur.com/sX2ES0P

为了更具特色,我试图在div中显示文字“Borte”

1 个答案:

答案 0 :(得分:2)

在活动结束时,只需执行(假设statusparsedData内的值):

document.getElementById("on").innerHTML = parsedData.status;

假设你在页面上有div,如果你没有,那么你必须先创建它:

var div = document.createElement("div")
div.innerHTML = parsedData.status;

document.body.appendChild(div);