繁体   English   中英

jQuery更改列内文本的颜色

[英]JQuery changing colour of text within columns

我的网页中有三列。 每列上都有一组三个正方形,正方形代表一种独特的颜色。 因此,当用户单击第1列中的红色时,第1列中的文本变为红色,如果为蓝色,则它将变为蓝色。 如果用户单击第2列中的绿色,则第2列中的文本将变为绿色。

我是jQuery的新手,所以我不确定自己是否做对了,并想知道这是否是最好的方法。

我想知道的是,无论如何都需要进行更改,因此每一列中只有一种样式称为“选择器”。 我还可以更改jQuery,使其不是3个单独的函数,是否有更简洁的方法?

谢谢。

是! CSS选择器都是可重用的! 您不应该创建具有完全相同的属性和值的多个类!

您需要的所有CSS类.col, .wrapper, .picker

然后在要在多个地方使用代码时使用jQuery而不是使用div id,请计算元素相对于触发事件的元素或$(this)

查看小提琴http://jsfiddle.net/WJ5DZ/1/

您可以这样尝试:

$(function () {
    $('.picker').css('background-color', function () { //Setup the background color for each picker square.
        return $(this).data('color'); //get its color from data attribute
    }).click(function () { //Chain it through for the click event
        $(this).closest('.content').css({ //get the parent content element where color needs to be applied
            color: $(this).data('color') //set the color as that of the clicked picker.
        });
    });
});

演示

在标记中,提供一个称为“说content的类以标识其自己的父内容。

<div class='col2 content' id="test1"> <!-- You don't need id if you are using this for selcting. 

删除所有picker1, 2 CSS规则和刚才的picker

使用closest将确保即使您计划将包装器添加到选择器中,仍然会选择您的实际内容div。

是的,有..将您所有的课程(picker1,picker2)更改为picker并删除ID(test,test1 ..)

尝试这个

   $('.picker').each(function(){
      var myColor = $(this).data('color');
      $(this).css({background: myColor })
   });
  $('.picker').click(function(){
     var myColor = $(this).data('color');
     $(this).parent().css({color: myColor});

  });

注意:您不需要each循环内的click事件

在这里摆弄

暂无
暂无

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

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