首页 > 解决方案 > 您如何唯一地定位函数实例的 html/css?

问题描述

您可以在不将 id 作为参数传递的情况下唯一地定位对象的新实例吗?

如果您从构造函数创建新对象并且每个实例都可以访问存储为构造函数中的变量的一些 html(表示),当创建对象的新实例并且从表示变量输出 html 时,您如何定位每个这些实例以独特的方式?您如何设计一个实例与另一个实例不同的样式?

function MyObj() {
  this.content = "<div class = 'someclass'>Some text </div>";
}

var newObj1 = new MyObj();
console.log(newObj1.content); //outputs Some text 

var newObj2 = new MyObj();
console.log(newObj2.content); //outputs Some text

如果您想针对所有新类的 css,您可以使用:

var target1 = $('.someclass').css('color,'orange');

但是如何以不同的方式定位一个目标呢?

标签: javascriptjquerycssobject

解决方案


这取决于您希望如何定位另一个实例。一种选择是使用:nth-child:first-child:last-child选择器。举个例子:

$('.someclass:nth-child(even)').css('color','orange');
$('.someclass:nth-child(odd)').css('color','blue');
$('.someclass:nth-child(1)').css('color','green');
$('.someclass:first-child').css('color','red');

推荐阅读