将Straight JS转换为JQuery

时间:2011-01-24 15:19:37

标签: javascript jquery json dom last.fm

我试图从last.fm API附加一些JSON数据,

我一直在几个阶段使用alert()来验证API是否正确解析,它是,

这使我得出结论getElementById()。appendChild()不起作用,下面是我设置的测试页面的URL:

http://mutant-tractor.com/tabtest.html

所以从这个直接的JS转到JQuery我被告知是最好的方法, 这就是说我对任何JQuery没有任何线索,我的JS知识基于我已经完成的一些基本Java ...

将它转换为工作JQuery有多简单/不简单? 我会对此表示赏心悦目,但我不知道该怎么做。

function calculateDateAgo(secAgo) {
 var agoString, agoRange, agoScaled;
 if(secAgo >= (agoRange = 60*60*24)) 
   agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"days":"day") + " ago";
 else if(secAgo >= (agoRange = 60*60))
   agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"hours":"hour") + " ago";
 else if(secAgo >= (agoRange = 60))
   agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"minutes":"minute") + " ago";
 else if(secAgo >= -60)
   agoString = "blastin' out now";
 else
   agoString = "soon ;)";
 return agoString;
}

function truncateName(name, l) {
return name.length > l ? name.substr(0,l-2) + "\u2026" : name;
}

function lfmRecentTracks(JSONdata) {

try { 
 var eImg, eLink, eSpan, divTag, eWrapper;
 var oTracks = new Array().concat(JSONdata.recenttracks.track);
 for (var i = 0; i < oTracks.length; i++) {
  //insert coverart image
  var spanTag  = document.createElement("span");
  document.body.appendChild(spanTag);
  spanTag.className = "lfmTrackImageCell tab_item";
  if(oTracks[i].image[1]["#text"] != "") {
   eImg = document.createElement("img");
   spanTag.appendChild(eImg);
   eImg.src = oTracks[i].image[1]["#text"];
   eImg.className = "lfmTrackImage";
  }else{
    eImg = document.createElement("img");
    spanTag.appendChild(eImg);
    eImg.src = "http://cdn.last.fm/flatness/icons/res/3/track.png";
    eImg.className = "lfmTrackImageNotFound";
  }
 }
for (var i = 0; i <>[lessthanhere] oTracks.length; i++) {
  //insert track link
  spanTag = document.createElement("span");
  spanTag.className = "lfmTrackInfoCell tabslider";
  eLink = document.createElement("a");
  eLink.appendChild(document.createTextNode( truncateName(oTracks[i].name, 25) ));
  //alert(truncateName(oTracks[i].name, 25));
  spanTag.appendChild(eLink);
  eLink.href = oTracks[i].url;
  //alert(oTracks[i].url);
  eLink.target = "new";
  eLink.className = "lfmTrackTitle";
  document.body.appendChild(spanTag);

  //insert artist name
  eSpan = document.createElement("span");
  eSpan.appendChild(document.createTextNode(truncateName(oTracks[i].artist["#text"], 22) ));
  //alert(truncateName(oTracks[i].artist["#text"], 22));
  eSpan.className = "lfmTrackArtist";
  document.body.appendChild(eSpan);

  //insert date
  eSpan = document.createElement("span");
  spanTag.appendChild(eSpan);
  eSpan.appendChild(document.createTextNode(   (typeof oTracks[i].date=="undefined"?"now playing":calculateDateAgo(new Date().getTime()/1000 - oTracks[i].date.uts))  )); 
  //alert((typeof oTracks[i].date=="undefined"?"now playing":calculateDateAgo(new Date().getTime()/1000 - oTracks[i].date.uts))); 
  eSpan.className = "lfmTrackDate"; 
  document.body.appendChild(eSpan);
 }  
} catch(e) {}
}

上述代码的唯一工作方式是使用document.body.appendChild()

我尝试在主体底部调用脚本并内联,以便允许完全加载DOM,但这些不起作用。

我试图将它们附加到的div是4个不同的div,即在for循环中每个循环需要引用不同的元素,

提前致谢! 迈尔斯

修改

HTML代码:

    <link href='css/style.css' rel='stylesheet' type='text/css' />
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'></script>
    <link rel="stylesheet" type="text/css" media="all" href="http://beta.mutant-tractor/wp-content/themes/toolbox/style.css" />
    <link href='/css/tabbedContent.css' rel='stylesheet' type='text/css' />
    <script src="/scripts/JQuery/tabbedContent.js" type="text/javascript"></script>
    <script type="text/javascript" src="/scripts/General/lastfmtest.js"></script>
</head>
<body>
    <aside class="widget">
    <h3>I'm listening to...</h3>

    <div class="tabbed_content">
        <div id="lfmArtRow" class="tabs">
            <div class="moving_bg">
                &nbsp;
            </div>
            <script type="text/javascript" src="http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&amp;user=mutant_tractor&amp;api_key=6b85edc3841f3d0935d9dfed9c556634&amp;limit=4&amp;format=json&amp;callback=lfmRecentTracks"></script>
        </div>
    </aside>
    <div id="lfmRecentTracks" style='padding: 15px;'>
        <div class="content">
            <div class="tabbed_content">
                <div class="slide_content">                     
                    <div class="tabslider">
                        <div class="sliding_info">Test 1
                        </div>
                        <div class="sliding_info">Test 2
                        </div>
                        <div class="sliding_info">Test 3
                        </div>
                    <div class="sliding_info">Test 4
                        </div>
                    </div>
                    <br style="clear: both" />
                </div>
            </div>
        </div>
    </div>
    <div id="test">
        </div>
</body>

<link href='css/style.css' rel='stylesheet' type='text/css' /> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'></script> <link rel="stylesheet" type="text/css" media="all" href="http://beta.mutant-tractor/wp-content/themes/toolbox/style.css" /> <link href='/css/tabbedContent.css' rel='stylesheet' type='text/css' /> <script src="/scripts/JQuery/tabbedContent.js" type="text/javascript"></script> <script type="text/javascript" src="/scripts/General/lastfmtest.js"></script> </head> <body> <aside class="widget"> <h3>I'm listening to...</h3> <div class="tabbed_content"> <div id="lfmArtRow" class="tabs"> <div class="moving_bg"> &nbsp; </div> <script type="text/javascript" src="http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&amp;user=mutant_tractor&amp;api_key=6b85edc3841f3d0935d9dfed9c556634&amp;limit=4&amp;format=json&amp;callback=lfmRecentTracks"></script> </div> </aside> <div id="lfmRecentTracks" style='padding: 15px;'> <div class="content"> <div class="tabbed_content"> <div class="slide_content"> <div class="tabslider"> <div class="sliding_info">Test 1 </div> <div class="sliding_info">Test 2 </div> <div class="sliding_info">Test 3 </div> <div class="sliding_info">Test 4 </div> </div> <br style="clear: both" /> </div> </div> </div> </div> <div id="test"> </div> </body>

5 个答案:

答案 0 :(得分:1)

document.getElementById()appendChild()一般在所有主要浏览器中均可正常工作,除了IE可以互换地使用idname的(可能无关的)问题。这里没有必要使用jQuery。

答案 1 :(得分:1)

没有理由这样做。 jQuery是JavaScript,但增加了功能。如果它在JavaScript中不起作用,翻译的jQuery也不会工作。这甚至没有提到翻译它的额外(不必要的)工作。

答案 2 :(得分:1)

而不是

document.body.appendChild( ... );

让您的函数找到您想要添加内容的<div>,如下所示:

var targetDiv = document.getElementById('lfmRecentTracks');

(确保确定页面上只有一个元素具有“id”值!!此外,为了IE,请确保该名称不是“name”属性在任何事情上。)

然后你应该能够做到这一点:

targetDiv.appendChild( whatever );

答案 3 :(得分:1)

我不会争论你是否需要jQuery。这不是必需品。但是,如果你想使用它,这就是你用jQuery做同样代码的方法:

            function calculateDateAgo(secAgo) {
             var agoString, agoRange, agoScaled;
             if(secAgo >= (agoRange = 60*60*24)) 
               agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"days":"day") + " ago";
             else if(secAgo >= (agoRange = 60*60))
               agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"hours":"hour") + " ago";
             else if(secAgo >= (agoRange = 60))
               agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"minutes":"minute") + " ago";
             else if(secAgo >= -60)
               agoString = "blastin' out now";
             else
               agoString = "soon ;)";
             return agoString;
            }

            function truncateName(name, l) {
            return name.length > l ? name.substr(0,l-2) + "\u2026" : name;
            }

            function lfmRecentTracks(JSONdata) {
                try { 
                    var eImg, eLink, eSpan, divTag, eWrapper, date;
                    var oTracks = new Array().concat(JSONdata.recenttracks.track);
                    for (var i = 0; i < oTracks.length; i++) {
                        //insert coverart image
                        var spanTag  = $('<span class="lfmTrackImageCell tab_item"></span>');
                        $("body").append(spanTag);
                        if(oTracks[i].image[1]["#text"] != "") {
                            eImg = $('<img src="'+oTracks[i].image[1]["#text"]+'" class="lfmTrackImage" />');
                            spanTag.appendChild(eImg);
                        }else{
                            eImg = $('<img src="http://cdn.last.fm/flatness/icons/res/3/track.png" class="lfmTrackImageNotFound" />');
                            spanTag.appendChild(eImg);
                        }
                     }
                    for (var i = 0; i <>[lessthanhere] oTracks.length; i++) {
                      //insert track link
                        spanTag = $('<span class="lfmTrackInfoCell tabslider"><a href='+oTracks[i].url+' target="new" class="lfmTrackTitle">'+truncateName(oTracks[i].name, 25)+'</a></span>');
                        //alert(truncateName(oTracks[i].name, 25));
                        //alert(oTracks[i].url);
                        $("body").append(spanTag);

                        //insert artist name
                        eSpan = $('<span class="lfmTrackArtist">'+truncateName(oTracks[i].artist["#text"], 22)+'</span>');
                        //alert(truncateName(oTracks[i].artist["#text"], 22));
                        $("body").append(eSpan);

                        //insert date
                        date = (typeof oTracks[i].date=="undefined"?"now playing":calculateDateAgo(new Date().getTime()/1000 - oTracks[i].date.uts));
                        eSpan = $('<span class="lfmTrackDate">'+ date +'</span>');
                        spanTag.append(eSpan);
                        //alert((typeof oTracks[i].date=="undefined"?"now playing":calculateDateAgo(new Date().getTime()/1000 - oTracks[i].date.uts))); 
                        $("body").append(eSpan);
                     }
                } catch(e) {}
            }

现在,我不保证生产中是否有效,但看起来是正确的。另外,我不确定你对i <>[lessthanhere] oTracks.length;部分做了什么,所以我把它留了。通常,它是i < oTracks.length;

答案 4 :(得分:0)

应该很简单。如果有一件事jQuery擅长(并且有很多),那就是DOM操作(即你正在尝试做的事情。)从这些教程开始

http://docs.jquery.com/Tutorials:How_jQuery_Works

http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

第二个将为您提供将HTML插入文档的良好介绍。之后,请查看文档的manipulation部分。