2013-02-23 16 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