使用.data()和.attr()的Changin数据值均失败

时间:2016-05-09 16:25:38

标签: jquery

我有这段代码:

<li>
    <a href="#" id="bca">
      <img width="60" height="35" class="brand img-responsive" alt="logo" 
        src="view/backoffice/assets/img/form-wizard/bca.png"
        data-src-retina="view/backoffice/assets/img/form-wizard/bca@2x.png">
    </a>
</li>

我有这个jquery:

$("#bri").click(function() {
    event.preventDefault();
    $("#bca").children().attr("src","view/backoffice/assets/img/form-wizard/bca-grey.png");
    $("#bca").children().attr("data-src-retina","view/backoffice/assets/img/form-wizard/bca-grey@2x.png");  
});

为什么我无法使用jquery更改data-src-retina值?我尝试使用这样的另一种方法但也失败了:

$("#bri").click(function() {
    event.preventDefault();
    $("#bca").children().attr("src","view/backoffice/assets/img/form-wizard/bca-grey.png");
    $("#bca").children().data("src-retina","view/backoffice/assets/img/form-wizard/bca-grey@2x.png");   
});

我在这里做错了什么?谢谢。

1 个答案:

答案 0 :(得分:1)

似乎你的代码工作正常:

$(document).ready(function() {
  $("#bri").click(function() {
    $("#bca").children().each(function() {
      alert("Old data-src-retina:" + $(this).attr("data-src-retina"));
    });
    event.preventDefault();
    $("#bca").children().attr("src", "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRE9BlrARaNurkqQCh1Y-CeyvAsqpFYVVUwIe_TpPhhJLglGK0aRHZuZw");
    $("#bca").children().attr("data-src-retina", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRUc0zJ7TAI81eAL8sitUl81v409oihvi3fRfnnbyzTbhYAJC33");
    $("#bca").children().each(function() {
      alert("New data-src-retina:" + $(this).attr("data-src-retina"));
    });
  });
});

Plunker:https://plnkr.co/edit/mlyous7dosRl9IN9ds7U