[英]Trying to change properties of another element within .click() function
I want to change the text color of an element when I click a button using jQuery. 当我使用jQuery单击按钮时,我想更改元素的文本颜色。 This code is not working, please help!
此代码不起作用,请帮忙!
$(document).ready(function() { $("p").click(function() { $(this).hide(); }); $("button").click(function() { $("#colorChange").style.color = "blue"; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="colorChange">I should(?) change color when you click mr. button</p> <button>clickme</button>
hope this help 希望这个帮助
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); $("button").click(function(){ $("#colorChange").css("color","blue"); }); }); </script> </head> <body> <p id="colorChange">I should(?) change color when you click mr. button</p> <button>clickme</button> </body> </html>
Try using $("#colorChange").css("color", "blue")
instead of $("#colorChange").style.color = "blue"
. 尝试使用
$("#colorChange").css("color", "blue")
代替$("#colorChange").style.color = "blue"
。
For more info, visit: https://api.jquery.com/css 有关更多信息,请访问: https : //api.jquery.com/css
The problem is this line: 问题是这一行:
$("#colorChange").style.color = "blue";
It should look like this: 它看起来应该像这样:
$("#colorChange")[0].style.color = "blue";
This is because the object returned from $("#colorChange")
is a jQuery Object . 这是因为从
$("#colorChange")
返回的对象是jQuery Object 。 The style property you wish to change is a member of a DOM Element , which can be retrieved from the jQuery Object with an array index or the get()
method. 您希望更改的style属性是DOM Element的成员,可以使用数组索引或
get()
方法从jQuery Object中检索该元素 。
Please try this, 请尝试一下
$("button").click(function(){
$("#colorChange").css("color","blue");
});
this one also works fine, 这个也很好用
$("button").click(function(){
$("#colorChange")[0].style.color= 'blue';
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.