2014-10-08 11 views
0

我正在努力編寫javascript代碼,它可以模擬一個程序打印可以被三整除的數字,乒乓可以被五整除的數字,乒乓可以被數字整除,否則就是打印數字。我有它的工作,但我知道我應該使用jQuery,以使其更高效。我一直在關注prepend方法的教程,並對其進行了一些閱讀,但我無法弄清楚如何將其實現到我的代碼中。任何指針?如何在jQuery中使用prepend函數使我的代碼更高效?

<ul> 
    <script> 
    ppCount = prompt("What number would you like me to ping-pong up to?"); 
    // document.write(console.log(ppCount)); 
    function pingPong (ppCount) { 
      for (var index = 1; index <= ppCount; index += 1) { 
       if (index % 3 === 0 && index % 5 === 0) { 
        document.write('<li>' + "ping-pong" + '</li>') 
       } else if (index % 3 === 0) { 
        document.write('<li>' + "ping" + '</li>') 
       } else if (index % 5 === 0) { 
        document.write('<li>' + "pong" + '</li>') 
       } else { 
        document.write('<li>' + index +'</li>') 
       } 
       document.write('<br>') 
      } 
     }; 
     pingPong(ppCount); 
    </script> 
</ul> 
+3

僅供參考,由於jQuery在DOM之上添加了一個額外的抽象層,因此它在運行時行爲方面通常效率較低。但是,你幾乎不會注意到這個區別。 *「但我不知道如何將其實現到我的代碼中」*那麼,你卡在哪裏?我們可以將您指回文檔,但由於您已經在查看它,因此您必須對您的實際問題進行更具體的描述。 – 2014-10-08 04:38:18

+1

'// document.write(console.log(ppCount));'< - 你想用那個做什麼?您不需要在document.write中包裝console.log。 – 2014-10-08 04:39:27

+0

$('body')。prepend('

  • '+「ping-pong」+'
  • ');應該工作,但取決於你想要的東西。但如上所述,並不意味着它更有效率。 – artm 2014-10-08 04:40:00

    回答

    0

    從外觀上看,您正在寫入文檔的內容 - 在運行中 - 文檔正在加載。

    即,document.write()寫入遇到的內容(在這種情況下,在<ul>內)。恐怕這是可以做到與jQuery一樣...


    如果你想在<ul>創建後要做到這一點,你可以這樣做:

    $(document).ready(function(){ 
        var ppCount = new Array(prompt("What number would you like me to ping-pong up to?")); 
        function pingPong(ppCount) { 
        for (var index = 1; index <= ppCount; index++) { 
         if (index % 3 === 0 && index % 5 === 0) { 
         $("ul").append('<li>ping-pong</li>') 
         } else if (index % 3 === 0) { 
         $("ul").append('<li>ping</li>') 
         } else if (index % 5 === 0) { 
         $("ul").append('<li>pong</li>') 
         } else { 
         $("ul").append('<li>' + index + '</li>') 
         } 
        } 
        }; 
        pingPong(ppCount); 
    }) 
    
    0

    http://jsfiddle.net/5kj1m493/

    <ul></ul> 
    

    $(function() { 
    $.each(new Array(prompt("What number would you like me to ping-pong up to?") * 1), 
        function(ind) { 
         var i = ind + 1; 
         var message = !(i % 5) && !(i % 3) ? 'ping-pong' : 
         (!(i % 5) ? 'pong' : (!(i % 3) ? 'ping' : i)); 
         $('<li>').html(message).appendTo($('ul'));   
        }); 
    }); 
    

    或與for循環))

    相關問題