j查询在点击时更改颜色

jQuery Change Color on click

本文关键字:颜色 查询      更新时间:2023-09-26

我是jQuery初学者,想要实现以下目标 - 每当我单击页面的任何元素时,我希望其中文本的颜色更改为红色。这就是我所拥有的,但它不起作用。令人惊讶的是,警报语句也没有打印任何内容。但是当我用另一个警报语句测试它时,它确实会执行。谢谢。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div>Cow</div>
    <div>Cat</div>
    <p>paragraph</p>
    <p>coconut</p>
    <script type="text/javascript" src="../Scripts/jquery-2.0.3.js"></script>
    <script type="text/javascript">
        $(this).click(function () {
            var v = $(this).text();
            alert(v); // this prints nothing !!!!
            $(this).css("color", "red");
        });
    </script>
</body>

如果将

单击处理程序附加到 document ,任何冒泡到文档的单击都将转到事件侦听器。如果您现在在侦听器中查找event.target,那将是启动事件的节点:

$(document).click(function (event) {
  $(event.target).css("color", "red");
});

示例:http://jsfiddle.net/E9H22/

如果您指定 body 元素(代替 this ),那么它可以工作:

$('body').click(function () {
    var v = $(this).text();
    alert(v); // this prints something, now.
    $(this).css("color", "red");
});

JS小提琴演示。

当然,您也可以使用:

$(this.document.body).click(function () {
    var v = $(this).text();
    alert(v); // this prints something, now.
    $(this).css("color", "red");
});

JS小提琴演示。

如果只希望单击的元素的文本变为红色:

$('body').click(function (e) {
    $(e.target).css("color", "red");
});

JS小提琴演示。

$(this).click(function () {

这是你的问题。

与其说this,不如说CSS选择器来指定哪些元素会改变颜色。

例如,您可以尝试

$('div').click(function() { // Will change the color of the divs
     var v = $(this).text();
     alert(v); // this prints nothing !!!!
     $(this).css("color", "red");
}); 
$('p').click(function() {  // Will change the paragraphs
    ...
}); 
$('p, div').click(function() {  // Will work for either one!
    ...
}); 
$('*').click(function() {  // Will work for any element on the page
    ...
}); 

$(this).click(function () {

"this"不是指