2015-06-18 37 views
-1

我想要使用此代碼:http://jsfiddle.net/kFu52/1/我不知道如何整合此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" lang="en" xml:lang="en"> 
 

 
<head> 
 
<title>Demo</title> 
 
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
 
<link href="Untitled-3.css" rel="stylesheet" type="text/css" /> 
 
</head> 
 

 
<body> 
 

 

 
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.js"></script> 
 

 
<script> 
 
$('.thumbs img').hover(function() { 
 
    var url = $(this).attr('src'); 
 
    $('#main').attr('src', url); 
 
}); 
 
</script> 
 

 

 
<div class="thumbs"> 
 
    <img src="http://lorempixel.com/sports/200/400" width="50" height="50"/> 
 
    <img src="http://lorempixel.com/city/200/400" width="50" height="50"/> 
 
    <img src="http://lorempixel.com/people/200/400" width="50" height="50"/> 
 
</div> 
 

 
<div class="main-img"> 
 
    <img id="main" src="http://lorempixel.com/people/200/400"/> 
 
</div> 
 

 

 
</body> 
 

 
</html>

非常感謝,我顯然很新的JQuery的。

+0

包內的文檔準備好你的代碼。 – Jai

回答

0

將它包裝在DOM準備好的事件中。否則,您的腳本將在元素呈現之前執行。

$(document).ready(function() { 
    $('.thumbs img').hover(function() { 
     var url = $(this).attr('src'); 
     $('#main').attr('src', url); 
    }); 
}); 
0

使用ready。這將在你的頁面中的所有元素加載後運行的readycallback內的代碼和hover事件被綁定在img.thumb

指定一個函數來執行當DOM完全加載。

$(document).ready(function() { 
    $('.thumbs img').hover(function() { 
     var url = $(this).attr('src'); 
     $('#main').attr('src', url); 
    }); 
}); 
0

您需要使用document-ready處理程序。目前您的代碼在加載DOM之前執行。其餘的代碼工作。

指定一個函數來執行當DOM完全加載。

$(function() { 
 
    $('.thumbs img').hover(function() { 
 
    var url = $(this).attr('src'); 
 
    $('#main').attr('src', url); 
 
    }); 
 
});
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.js"></script> 
 

 

 
<div class="thumbs"> 
 
    <img src="http://lorempixel.com/sports/200/400" width="50" height="50" /> 
 
    <img src="http://lorempixel.com/city/200/400" width="50" height="50" /> 
 
    <img src="http://lorempixel.com/people/200/400" width="50" height="50" /> 
 
</div> 
 

 
<div class="main-img"> 
 
    <img id="main" src="http://lorempixel.com/people/200/400" /> 
 
</div>

0

儘管答案都有效,我已經習慣了使用以下命令:

jQuery(function($) { 
    // your code here. 
}); 

我不很瞭解的區別,我喜歡簡單這個比ready好。如果有人願意在評論中提供更多信息,我會編輯我的答案。

該語法允許您使用其他JS庫也使用$作爲標識符。將所有的jQuery代碼封裝在內部,你將不會與另一個庫發生衝突。 從jQuery's API

然而,該處理程序傳遞給。就緒()方法可以採取一個參數,其被傳遞全局jQuery對象。這意味着我們可以在不影響其他的代碼我們。就緒()處理的範圍內對象重命名爲:

+0

只需通過https://api.jquery.com/ready/ _使用另一個JavaScript庫時,我們可能希望調用$ .noConflict()來避免名稱空間困難。當這個函數被調用時,$快捷方式不再可用,迫使我們每次通常寫$都寫jQuery。但是,傳遞給.ready()方法的處理程序可以接受一個參數,該參數傳遞給全局jQuery對象。這意味着我們可以在.ready()處理程序的上下文中重命名對象,而不會影響其他代碼:_ – Satpal

+0

謝謝!我現在正在看一看。 – D4V1D

+0

@Satpal我可以看到他們提到了'jQuery(document).ready(function($){'但它與我提供的稍有不同。你是否知道這兩者之間的區別? – D4V1D

相關問題