【问题标题】:Grails: JS function to change src of img is not respondingGrails:更改img src的JS函数没有响应
【发布时间】:2012-07-28 22:47:41
【问题描述】:

我正在尝试在特定条件下更改 img 的 src。我知道条件适当地返回 true,因为我之前在 alert() 中写过。由于某种原因,该功能不会更改 img 的 src 并动态更新页面。这可能与我使用 jquery 库的事实有关吗?我认为您仍然可以使用 stand js 语法。这是我的代码 sn-ps 和来自 google chrome 的相应源代码。

.gsp:

<script type="text/javascript">
function onSuccess(data){
    if(data.hasHearted){
        document.getElementById("changer${user.id}").src = "${resource(dir: "images/images", file: "heart_red.png")}";
    }       
}

<figcaption id="secondcap" onClick="${remoteFunction(controller:'user', action:'heart', onSuccess: 'onSuccess(data)', params:[userID:user.id])}">               
            <img id="changer${user.id}" src="${resource(dir: "images/images", file: "heart.png")}" alt="heart">
</figcaption>

Chrome 源代码(出于隐私考虑,我省略了一些内容):

<script type="text/javascript">
function onSuccess(data){
    if(data.hasHearted){
        $('#changer3').attr('src','/Personably/static/images/images/heart_red.png');
    }       
}
</script>

<div class="persons">   
<figure class="user_image">         
    <img class="user_profile_pic" src="omitted for privacy..." onmouseover="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/hasHearted',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});"/>  
    <figcaption id="firstcap">
            Omitted for privacy...
    </figcaption>               
    <figcaption id="secondcap" onClick="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/heart',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});">                
            <img id="changer3" src="/Personably/static/images/images/heart.png" alt="heart">
    </figcaption>
</figure>
</div>

【问题讨论】:

    标签: javascript html ajax grails


    【解决方案1】:

    由于您使用的是 jquery,您是否尝试过使用 jquery id 选择器 $(“#id”) 和/或 jquery .attr 函数?

    http://api.jquery.com/id-selector/

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

    【讨论】:

      【解决方案2】:

      我不确定在页面加载后更改 src 属性会改变用户看到的内容,即使它更改了代码,因为文档已经加载。

      相反,您可能应该将两个图像(heart.png 和 heart_red.png)都放在页面上,然后根据控制器操作的输出使用样式隐藏/取消隐藏它们。 jquery .toggle(Boolean) 方法对于这样的东西非常有用。 http://api.jquery.com/toggle/

      在你的 JavaScript 函数中,你可以有类似的东西:

      $('#heart3').toggle(!data.hearted);
      $('#heart_red3').toggle(data.hearted);
      

      那么,当data.hearted为真时,红心会显示,普通心会隐藏。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        • 2020-07-21
        • 2022-01-15
        • 2023-03-21
        • 2018-09-15
        • 2012-05-26
        相关资源
        最近更新 更多