在JQuery中设置Src属性的正确方法是什么?

时间:2010-12-08 17:50:52

标签: javascript jquery html

假设我有以下HTML:

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

我想将src切换为bar2.jpg

我可以这样做吗?

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

或者我必须这样做吗?

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

谢谢!

5 个答案:

答案 0 :(得分:48)

执行此操作时:

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

之前的src已被替换。

所以你不需要:

$("#foo").removeAttr("src");

You can confirm it out here

答案 1 :(得分:4)

只需.attr('src', 'foo'),因为您无论如何都要分配src。如果您不完全需要,请仅删除该属性。

答案 2 :(得分:4)

第一个很好,没有理由先删除它。

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

$。attr既可以获取现有属性又可以更改它(取决于是否有一个或两个参数)。您的情况正是他的第二个功能所针对的,属性'src'并不特殊。

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

答案 3 :(得分:0)

<!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>

答案 4 :(得分:0)

即使是mediaelement玩家,也有:

  $("#player5").attr("poster", "/images/poster/Azadi.jpg");