2016-11-10 73 views
0
<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <title> 
     </title> 
     <meta charset="utf-8" /> 
     <link rel="stylesheet" type="text/css" href="css/custom.css" /> 
    </head> 
    <body> 
     <button id="myButton">My Button</button><br /><br /> 
     <span id="myPara"> My paragraph</span>  
    <script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script> 
    <script type="text/javascript" src="js/custom.js" ></script> 
    </body> 
</html> 
下面

custom.css样式代码不工作

#myPara{ 
    border: 1px solid black; 
    color: black; 
    padding: 5px; 
} 

下面的代码是在custom.js

$('#myButton','#myPara').on('click',function(){ 
    $(this).css('border-color','white').css('background','black').css('color','white'); 
}); 

我想申请给定的CSS如图jQuery代码的代码。

它也没有在控制台中给出任何错误,这使我很难找到错误。

在我的浏览器中,点击上没有显示CSS效果。

我是jQuery的初学者。

回答

6
$('#myButton','#myPara').on('click',function(){ 

在这一行中,第一个参数是CSS选择器,第二个参数用于上下文。你可能需要这个:

$('#myButton,#myPara').on('click',function(){ 

你可以找到更多关于how the $() function works here

0

您正在将context设置为字符串,"#myPara"jQuery()调用。使用

$('#myButton').on('click',function() { 
    $("#myPara") 
    .css({borderColor:'white', background:'black', color:'white'}); 
}); 
0

逗号应该像

$('#myButton, #myPara').on('click',function(){ 
$(this).css('border-color','white').css('background','black').css('color','white'); 
}); 
+0

你在语法问题上是正确的,但是你的解决方案并不能真正解决问题。 –

4

Youv'e选择内部编码它不正确......

$('#myButton').on('click',function(){ 
    $('#myPara').css({ 
     borderColor: 'white', 
     backgroundColor: 'black', 
     color: 'white'}); 
}); 

在jQuery的正确的格式结合您的CSS属性,并检查选择。在你的jQuery this指的是按钮和段落。

$('#myButton').on('click',function(){ 
 
     $('#myPara').css({ 
 
      borderColor: 'white', 
 
      backgroundColor: 'black', 
 
      color: 'white'}); 
 
    });
#myPara{ 
 
    border: 1px solid black; 
 
    color: black; 
 
    padding: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="myButton">My Button</button><br /><br /> 
 
     <span id="myPara"> My paragraph</span>

如果您想在要么按钮被点击的段落,您需要更改jQuery选择发生变化....注意引号和逗号在选择器中。这将改变所点击的内容,而不是每次都改变段落内容。

$('#myButton, #myPara').on('click', function(){ 
 
     $(this).css({ 
 
      borderColor: 'white', 
 
      backgroundColor: 'black', 
 
      color: 'white'}); 
 
    });
#myPara{ 
 
    border: 1px solid black; 
 
    color: black; 
 
    padding: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="myButton">My Button</button><br /><br /> 
 
     <span id="myPara"> My paragraph</span>

0

它看起来像你想“如果单击该按钮,然后#myPara改变颜色”这可以用下面的代码来完成:

jQuery('#myButton').click(function(){ 
     jQuery('#myPara').addClass('active'); 
    }); 

    .active { 
     border-color: white; 
     background: black; 
     color: white; 
    } 

添加类似乎就像一个更有效的方式去做这件事。这样,添加/删除/编辑样式变得更加容易。