Подтвердить что ты не робот

Какой правильный способ установить атрибут Src в JQuery?

Предположим, что у меня есть следующий HTML:

<img id="foo" src="bar1.jpg"/>

Я хотел бы переключить src на bar2.jpg

Могу ли я это сделать?

$("#foo").attr("src", "bar2.jpg");

Или мне нужно это делать?

$("#foo").removeAttr("src");
$("#foo").attr("src", "bar2.jpg");

Спасибо!

4b9b3361

Ответ 2

Просто сделайте .attr('src', 'foo'), потому что вы назначаете src независимо. Удалите атрибут, если он вам не нужен.

Ответ 3

Первый wey просто отлично, нет причин сначала его удалять.

$("#foo").attr("src", "bar2.jpg");

$. attr служит как для получения существующего атрибута, так и для его изменения (в зависимости от того, есть ли один или два аргумента). Ваша ситуация - именно то, для чего предназначена вторая функциональность, а атрибут 'src' не является особенным.

http://api.jquery.com/attr/

Ответ 4

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.main{
    position:relative;
}
.second{
position:absolute;
top:20px;
left:720px;
}
.third{
    position:absolute;
top:290px;
left:720px;
}
.fourth{
    position:absolute;
top:100px;
left:1030px;
}
.firstarrow{
    position:absolute;
top:20px;
left:1100px;
}
.secondarrow{
    position:absolute;
top:20px;
left:1030px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script> 
$(document).ready(function(){
  $(".firstarrow").on('click', function() {
   var pos1 = $('.first img').attr('src');
   var pos2 = $('.second img').attr('src');
   var pos3 = $('.third img').attr('src');
   var pos4 = $('.fourth img').attr('src');
   $('.third img').attr('src', pos1);
   $('.fourth img').attr('src', pos3);
   $('.second img').attr('src', pos4);
   $('.first img').attr('src', pos2);
});

  $(".secondarrow").on('click', function() {
   var pos1 = $('.first img').attr('src');
   var pos2 = $('.second img').attr('src');
   var pos3 = $('.third img').attr('src');
   var pos4 = $('.fourth img').attr('src');
   $('.third img').attr('src', pos4);
   $('.fourth img').attr('src', pos2);
   $('.second img').attr('src', pos1);
   $('.first img').attr('src', pos3);
});

});
</script>

</head>

<body>
<div class="main">
<div class="first">
<img src="img1.jpg" alt="" width="700" height="511" />
</div>
<div class="second">
<img src="img2.jpg" alt="" width="300" height="250" />
</div>
<div class="third">
<img src="img3.jpg" alt="" width="300" height="250" />
</div>
<div class="fourth">
<img src="img4.jpg" align="" width="300" height="400"  />
</div>
<a href="#"><div class="firstarrow"><img src="ar1.jpg" width="48" height="48" /></div></a>
<a href="#"><div class="secondarrow"><img src="ar2.jpg" width="48" height="48" /></div></a>
</div>

</body>
</html>