繁体   English   中英

jQuery单击更改颜色

[英]jQuery Change Color on click

我是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”不是指<script>标签所在的位置,而是指窗口对象。 所以从本质上讲,您的代码可以这样做:

$(window).click(function (){

如果要使母牛变成红色,请在单击它时将HTML更改为:

<div id="cow">Cow</div>

和您的脚本:

// callback needs to be inside $(document).ready(fn) to make sure the DOM is ready when trying to use it
$(document).ready(function () {
    // and we need to refer to an explicit element
    $('#cow').click(function (){
        // now we can refer to "this", since inside the click handler's context is the clicked element
        $(this).css({color: 'red'});
    });
}

您需要将其包装在文档ready语句中,并将点击侦听器附加到实际元素上:

$(function(){
  $("*").click(function () {
    $(this).css("color", "red");
  });
});

选择器的外观可能类似于$("div, p").click(...)具体取决于要激活的元素。

$(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
    ...
}); 

您必须指定要向其添加点击事件的元素。 例如,这将适用于所有div元素:

$('div').click(function () {
    $(this).css("color", "red");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM