2011-12-19 66 views
0

我的朋友給了下面的代碼是在這裏工作真棒http://jsfiddle.net/WVLE2/如何運行下面的jQuery代碼

我使用一個HTML頁面,如下,但它不工作嘗試同樣的。我正在學習jQuery的階段。任何人請幫助我如何在下面的腳本中執行聊天滾動。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<script src="http://code.jquery.com/jquery-1.7.1.min.js" ></script> 
<script src="http://code.jquery.com/jquery-1.7.1.js" ></script> 
<title>Chat scroll test</title> 
<style type="text/css"> 
#chat 
{ 
    width: 200px; 
    height: 200px; 
    border: 1px solid black; 
    overflow-y: auto; 
} 
</style> 
<script> 
monitor = function() { 
    var $this = $(this), 
     wrap = $this.find('.wrapper'), 
     height = $this.height(), 
     maxScroll = wrap.height() - height, 
     top = $this.scrollTop(); 
    if (maxScroll === top) { 
     $this.addClass('atBottom'); 
    } else { 
     $this.removeClass('atBottom'); 
    } 
} 
    window.setInterval(function() { 
     monitor.call($('#chat').get(0)); 
    }, 350); 
$('#chat').bind('addMessage', function(e, message) { 
    var $this = $(this), 
     top = $this.scrollTop(), 
     scroll = $this.hasClass('atBottom'); 
    $this.find('.wrapper').append(message); 
    if (scroll) { 
     var wrap = $this.find('.wrapper'), 
      height = $this.height(), 
      maxScroll = wrap.height() - height 
     $this.scrollTop(maxScroll); 
    } 
}) 
$('button').click(function() { 
    $('#chat').trigger('addMessage', 'asdgagasdg<br/>'); 
}); 

</script> 
</head> 

<body> 
<div id="chat"> 
    <div class="wrapper"> 
     adsgasgda<br/> 
     adsgasg<br/> 
     asd<br/> 
     adsgasgda<br/> 
     adsgasg<br/> 
     adsgasgda<br/> 
     adsgasg<br/> 
     adsgasgda<br/> 
     adsgasg<br/> 
     adsgasgda<br/> 
     adsgasg<br/> 
     adsgasgda<br/> 
     adsgasg<br/> 
     adsgasgda<br/> 
     adsgasg<br/> 
    </div> 
</div> 
<button>Add a line</button> 
</body> 
</html> 

而這個結果甚至沒有一條線添加按鈕點擊。輸出與HTML一樣,但jQuery不起作用。

+0

我是否需要任何編譯器/除了運行jQuery代碼之外的任何東西? – 2011-12-19 09:25:12

+0

你包含兩次jQuery。一個開發者和一個最小化。只要min是好的。 – 2011-12-19 09:31:02

+0

@EmreErkan - 謝謝Emre。兩者有什麼區別? – 2011-12-19 09:33:43

回答

2
jQuery(document).ready(function($) { 
    /* your jQuery code */ 
}); 
+0

:)它的工作!謝謝micha。 – 2011-12-19 09:26:40

1

將其添加到document.ready可能會得到它的工作。你馬上就選擇了一些東西;你必須等待DOM準備好做到這一點。當$('button').click()執行,按鈕尚不存在這樣的jQuery的功能,以解決您的選擇沒有找到匹配對象,因此代碼什麼也不做

jQuery(function($) { 

    // your jquery code goes here 

}); 
+0

從micha找到同樣的結果。不管怎麼說,多謝拉! :) – 2011-12-19 09:28:10

1

執行代碼文檔之前準備好,因此。你有幾種選擇:

1)你可以將你的<script>標籤和生成的代碼移到HTML之後(在<body>的末尾),以便在代碼執行時對象已經存在。

2)您可以在等待該文件以備調用這樣的代碼之前準備處理程序包事件處理程序的代碼:

$(document).ready(function() { 
    // put your code here 
}); 

這類似於使用window.onload = function() {};等待文件要加載,但jQuery的方法會比window.onload更早執行(jQuery的方法不會等待所有圖像加載,只是爲了解析DOM並準備好進行操作)。