【问题标题】:Change element css with jQuery without using classes or ids?在不使用类或 id 的情况下使用 jQuery 更改元素 css?
【发布时间】:2015-06-29 01:08:12
【问题描述】:

假设我们有未知数量的 div 元素。当我们单击元素时,该元素必须更改其背景颜色。如何做到这一点没有使用ids

注意:我发现了一些类似主题的问题,但它们不是我想要的。

我的意思是:

$(element).click(
    function(){
       $(element).css("background-color","#DDDDDD");
    }
);

HTML:

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

CSS:

div{
height:10px;
width:10px;
float:left;
border-radius:50%;
margin:2px;
background-color:#00A2E8;
}

DEMO

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

您已经很接近了,只需在函数中引用元素本身即可。

$("div").on("click",
    function(){
       $(this).css("background-color","#DDDDDD");
    }
);

【讨论】:

    【解决方案2】:

    像这样?

    $('div').click(function() {
      $(this).css('background-color', '#DDDDDD');
    });
    

    https://jsfiddle.net/ooyjLsy4/2/

    【讨论】:

      【解决方案3】:

      您可以在 jquery 中使用“this”来完成您的要求。

      $('div').click(
          function(){
            $(this).css("background-color","{{Your Color}}");
          }
      );
      

      【讨论】:

        【解决方案4】:

        如果要获取某个类型的所有元素,可以直接使用它们的名字$('div')$('a')$('span')等。

        如果您有一个事件(clickmouseoverchange 等),您只需在该事件块中使用 $(this) 即可访问触发该事件的特定控件。

        因此你应该有这个:

        $('div').click(
            function(){
                $(this).css("background-color","#DDDDDD");
            }
        );
        

        【讨论】:

          【解决方案5】:

          您正在寻找的是 jquery 中的元素选择器。只需执行 $("div") 即可选择所有 div 元素。有关选择器的更多信息,请访问this page

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-29
            • 2012-07-12
            • 1970-01-01
            • 2010-09-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-15
            相关资源
            最近更新 更多