在JavaScript中更改div属性以获取索引值

时间:2016-12-05 23:06:12

标签: javascript jquery html css

我正在尝试在JavaScript中更改div类switch-selection的左边距填充值。我的JavaScript函数中的以下内容更改了所有值。

var ind = 1; //getting index from php variable '1' is just an example

$(".switch-selection").css("paddingLeft","60px");

我只需要更改当前index值的值。我试过了:

$(".switch-selection")[ind].css("paddingLeft","60px");

但这给了我一个错误。我错过了什么吗?

3 个答案:

答案 0 :(得分:1)

使用eq()将其保留为jQuery对象,因为css()是一个jQuery方法。

$(".switch-selection").eq(ind).css("paddingLeft","60px");

答案 1 :(得分:1)

其他回复解决了问题的索引部分。但是,元素左侧填充的CSS属性为padding-left,而不是paddingLeftpaddingLeft Javascript 属性名称。

答案 2 :(得分:0)

您可以使用 :eq() 选择器或 .eq() 方法来指定元素的索引:

$(".switch-selection:eq("+ind+")").css("paddingLeft","60px");
//OR
$(".switch-selection").eq(ind).css("paddingLeft","60px");

希望这有帮助。



var ind=2;

$(".switch-selection:eq("+ind+")").css("paddingLeft","60px");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="switch-selection">DIV 1</div>
<div class="switch-selection">DIV 2</div>
<div class="switch-selection">DIV 3</div>
<div class="switch-selection">DIV 4</div>
<div class="switch-selection">DIV 5</div>
&#13;
&#13;
&#13;