2017-08-18 108 views
-2

我正在學習javascript和jquery。我最近發現了DOM遍歷。但是當我爲它編寫代碼時,它只是沒有響應。 的代碼是:我的JavaScript不適用於dom遍歷

<!DOCTYPE html> 
<head> 
<title>Test</title> 

</head> 
<body> 
<script> 

$('div').onclick = function pi() { 
var p = document.getElementsByClassName('.p'); 

p.value("hello guys"); 
}; 

</script> 
<div style="background-color:blue; height:1000px; width:100%px;"> 
</div> 
<div style="height: 600px; background-color: aqua;width: auto;"> 
<p style="color:black; font-size: 40px;" class="p">d 
</p> 
</div> 
</body> 
</html> 
+1

取出點,'document.getElementsByClassName( 'P ')'應該是'document.getElementsByClassName(' P')' –

+1

孤單......錯得太多了...... –

+1

錯誤的數量太高了,我甚至都不知道。 – Dellirium

回答

-1

讓我們通過的問題:

1)您沒有包括jQuery的任何地方,所以你不能使用它。如果你想使用它,你需要添加一個腳本標記(在<head>標籤之間鑑於你目前使用的)鏈接到它 - 是這樣的:

<script 
    src="https://code.jquery.com/jquery-2.2.4.js" 
    integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" 
    crossorigin="anonymous"></script> 

2)這是現在jQuery的onclick(如何這實際上是click )的作品。 click是接受函數的函數。當用戶點擊目標時,您傳遞給click的功能將被執行。您的代碼將被重寫jQuery的click,應該改爲:

$('div').click(function pi() { 
    // code 
}) 

3)它不禁止或什麼,但既然你已經使用jQuery,它不會使一噸的感覺回落到本地DOM獲取API,如getElementsByClassName。我建議你改用$('.p')

$('div').click(function pi() { 
    // it's good to prefix jquery collection variables with a $ 
    // makes it obvious what is in them 
    var $p = $('.p') 
}) 

側面說明你可以只使用$('p')和查詢基於標籤名,這避免分配冗餘的類名

4).value()既不是一個jQuery方法或一種本地方法。 jQuery有一個val()方法,但用於設置輸入元素的value屬性,如select,input等。您可能想要執行的操作是更改p標記的文本。用jQuery將是$('p').text('new text')。請注意,通話將改變文本ALLp元素,或class="p"元素在你的情況:

$('div').click(function pi() { 
    var $p = $('.p') 
    $p.text('hello guys') 
}); 

希望這有助於你對你的方式

+0

@BenFortune感謝您指出,不知道我錯過了那一個!更新 –

-1

有三個錯誤,我在這裏找到。

  1. 看起來你使用的是jQuery,所以在jQuery標籤中插入jQuery文件。
  2. 按類名稱調用時,不應使用「.p」。
  3. 一些語法錯誤

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<title>Test</title> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<script> 
 
$(document).ready(function(){ 
 
$('div').click(function(){ 
 

 
var p = document.getElementsByClassName('p'); //returns an Array with the class name "p" 
 
p[0].innerHTML = "Hello Guys"; // first element of all element in "p" array 
 

 
//or you could use the jquery way mentioned down below 
 

 
// $('.p').html("Hello Guys"); 
 
    
 
}); 
 
}); 
 
</script> 
 

 
</head> 
 
<body> 
 
    <div style="background-color:blue; height:100px; width:100%px;"> 
 
    </div> 
 
    <div style="height: 100px; background-color: aqua;width: auto;"> 
 
    <p style="color:black; font-size: 40px;" class="p">d</p> 
 
    </div> 
 
</body> 
 
</html>