2013-02-23 43 views

回答

1

之前,你的DOModel被讀取並準備進行操作

使用文檔ready功能

$(function(){ // DOM ready to be manipulated 

    $('div#thumbs img').click(function(e) { 
     e.preventDefault(); //stop link from navigating 
     $('#mainimg img').prop('src', this.src); 
    }); 

}); 

此外,在你的代碼,我看不到任何聯繫,所以實際上你的jQuery代碼運行你不需要任何return false而不是event-preventDefault()(我用過)

http://api.jquery.com/ready/

+0

工作很好,謝謝! – matture 2013-02-23 20:21:32

1

包裝你的jQuery在document ready call

$(document).ready(function() { 
    $('div#thumbs img').click(function() { 
     $('#mainimg img').prop('src', $(this).prop('src')); 
     return false; //stop link from navigating 
    }) 
}); 

的jsfiddle自動爲您完成此這就是爲什麼它在那裏工作。

1

放入準備好方法代碼:

$(document).ready(function(){ 
    $('div#thumbs img').click(function() { 
    $('#mainimg img').prop('src', $(this).prop('src')); 
    return false; //stop link from navigating 
    }) 
}); 

你實例化你的代碼之前的DOM元素已經準備就緒。

+1

我沒有倒下你,但我可以看到爲什麼有人會。你需要解釋你的第二個例子(順便說一下,.live()已經被棄用,而.on())將需要在DOM中創建div之後運行。在此之前的任何地方都是無用的。 – j08691 2013-02-23 19:54:51