我的HTML:
<ol class="flex-control-nav flex-control-thumbs">
<li>
<img src="images/test.gif" class="flex-active" draggable="false">
</li>
<li>
<img src="images/test.gif" draggable="false" class="">
</li>
<li>
<img src="images/test.gif" draggable="false" class="">
</li>
</ol>
我想更改以下图片scr
:
first li to images/car.jpeg
second li to images/bus.jpeg
first li to images/boat.jpeg
我想使用第n个选择器或
eq
函数完成此操作,而不是使用 每个功能。我可以在第一个li
内选择相似的图像 类flex-control-thumbs
,图像在类的第二个li
内flex-control-thumbs
等。
请帮我用jQuery,CSS nth选择器完成此操作。
答案 0 :(得分:3)
试试这个:
$('.flex-control-nav.flex-control-thumbs img').eq(0).attr('src','images/car.jpeg');
$('.flex-control-nav.flex-control-thumbs img').eq(1).attr('src','images/bus.jpeg');
$('.flex-control-nav.flex-control-thumbs img').eq(2).attr('src','images/boat.jpeg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="flex-control-nav flex-control-thumbs">
<li>
<img src="images/test.gif" class="flex-active" draggable="false">
</li>
<li>
<img src="images/test.gif" draggable="false" class="">
</li>
<li>
<img src="images/test.gif" draggable="false" class="">
</li>
</ol>
答案 1 :(得分:2)
更改所有图片的src
:
var images = ['car.jpeg','bus.jpeg','boat.jpeg'];
$('img').each(function(i){
$(this).attr('src','images/'+images[i])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="flex-control-nav flex-control-thumbs">
<li>
<img src="images/test.gif" class="flex-active" draggable="false" alt="one">
</li>
<li>
<img src="images/test.gif" draggable="false" class="" alt="two">
</li>
<li>
<img src="images/test.gif" draggable="false" class="" alt="three">
</li>
</ol>
使用src
更改特定图片的eq()
:
var list = $('.flex-control-nav.flex-control-thumbs > li > img');
list.eq(1).attr('src','images/bus.jpeg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="flex-control-nav flex-control-thumbs">
<li>
<img src="images/test.gif" class="flex-active" draggable="false" alt="one">
</li>
<li>
<img src="images/test.gif" draggable="false" class="" alt="two">
</li>
<li>
<img src="images/test.gif" draggable="false" class="" alt="three">
</li>
</ol>
答案 2 :(得分:2)
首先选择flex-control-nav中包含的li。然后使用eq(index)更改图像源。这将为您提供第一个li图像的索引
a =$('.flex-control-nav li');
a.eq(0).attr('src','images/car.jpeg');
a.eq(1).attr('src','images/bus.jpeg')
答案 3 :(得分:1)
var images = document.querySelectorAll('li img');
var img = ['images/car.jpeg','images/bus.jpeg','images/boat.jpeg'];
var indx = 0;
images.forEach(function(el){
el.src = img[indx++];
})
<ol class="flex-control-nav flex-control-thumbs">
<li>
<img src="images/test.gif" class="flex-active" draggable="false">
</li>
<li>
<img src="images/test.gif" draggable="false" class="">
</li>
<li>
<img src="images/test.gif" draggable="false" class="">
</li>
</ol>