为什么我的JavaScript代码拒绝在我的网站上运行



我的HTML文档如下:

<!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');
});​

为什么我的脚本没有在我的网站上运行?

你需要把jQuery包装在一个文档中,你可以使用$(this),因为它是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 comment -

$(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>

您在嵌套的代码行中缺少#选择器:

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

这将使所有p元素变成黄色背景。如果您只想要用户单击的元素,那么使用$(this):

引用"选定"对象。
$('#steps > p').on('click' , function(){
    $(this).css('background', 'yellow');
});

脚本应该在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>

最新更新