2016-08-19 50 views
-3

以下是我的HTML文件看起來像什麼:爲什麼我的JavaScript代碼拒絕在我的網站上運行?

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
    <script src="scripts/homepage-script.js"></script> 
</head> 

<body> 
<div id="how-it-works"> 
    <p>How It Works</p> 
    <img src="some-imageurl"> 
    <div id="steps"> 
    <p>Step 1</p> 
    <p>Step 2</p> 
    <p>Step 3</p> 
</div> 

這裏是我的腳本:

$('#steps > p').on('click' , function(){ 
    $('steps > p').css('background', 'yellow'); 
});​ 

爲什麼沒有在我的網站上運行我的腳本?

+3

您在第二個選擇器中缺少'#'符號.... –

+3

因爲您在DOM準備好之前正在運行它嗎? https://learn.jquery.com/using-jquery-core/document-ready/ – j08691

回答

1

你需要用jQuery的文檔中準備就緒,你可以使用$(本),因爲它是在onclick事件針對性:

$(document).ready(function(){ 
    $('#steps > p').on('click',function(){ 
      $(this).css('background', 'yellow'); 
    });​ 
}) 

但我會建議是有一個亮點類,它是然後在onclick事件中切換;

//CSS 
.highlight{background:yellow} 


$(document).ready(function(){ 
    $('#steps > p').on('click',function(){ 
      $(this).toggleClass('highlight'); 
    });​ 
}) 

這種方式你添加/刪除類而不是改變元素CSS。

如果您需要將高光類在DIV添加到所有p的按@Phil評論 -

$(document).ready(function(){ 
    $('#steps > p').on('click',function(){ 
     $('#steps > p').toggleClass('highlight'); 
    });​ 
}) 

$(document).ready(function(){ 
 
    $('#steps > p').on('click',function(){ 
 
      $(this).toggleClass('highlight'); 
 
    }); 
 
})
.highlight{background:yellow}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
    <script src="scripts/homepage-script.js"></script> 
 
</head> 
 

 
<body> 
 
<div id="how-it-works"> 
 
    <p>How It Works</p> 
 
    <img src="some-imageurl"> 
 
    <div id="steps"> 
 
    <p>Step 1</p> 
 
    <p>Step 2</p> 
 
    <p>Step 3</p> 
 
</div> 
 
    </body> 
 
    </html>

+0

你怎麼知道OP不想將所有**段落變成黃色? – Phil

+0

公平點@菲爾 – gavgrif

+0

這是jquery。不是JavaScript。 – 2016-08-19 00:42:01

0

你缺少你的嵌套的#選擇代碼行:

$('#steps > p').css('background', 'yellow');

這將使全部p元素變爲黃色背景。如果你只是想在用戶點擊的元素,然後引用了「選擇」的對象與$(this)

$('#steps > p').on('click' , function(){ 
    $(this).css('background', 'yellow'); 
}); 
+1

仍然無法工作,因爲腳本在元素存在之前運行 – Phil

0

腳本應該是DIV之後。

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 

</head> 

<body> 
<div id="how-it-works"> 
    <p>How It Works</p> 
    <img src="some-imageurl"> 
    <div id="steps"> 
    <p>Step 1</p> 
    <p>Step 2</p> 
    <p>Step 3</p> 
</div> 

<!--The script should be after the div.--> 
<script src="scripts/homepage-script.js"></script> 
相關問題