2016-08-19 58 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> 
相关问题