【问题标题】:Change image src with jquery使用 jquery 更改图像 src
【发布时间】:2012-08-07 12:05:43
【问题描述】:

我有这个代码:

function EnableiPad(event) {
    var id = $(event.currentTarget).attr("data-id");
    var status = $(event.currentTarget).attr("data-status");    
    $.post("/Ipad/ChangeStatus", { id: id, enable: status }, onAjaxSuccess);
};
function onAjaxSuccess(data) {
    var status = $(".button-enable").attr("data-status");

    if (status == 'true') 
    {
        $('#statusImg').attr("src", '/Content/img/disable.png');
    }
    else 
    {
        $('#statusImg').attr("src", '/Content/img/enable.png');
    }
}

但它不会改变图像 - $('#statusImg').attr("src", '/Content/img/disable.png');

更新

这是我的图片:

@if (iPad.Enabled)
{
    <button  class="button-enable" data-original-title="Show timetable"  data-id="@iPad.Id" data-status="false" class="btn btn-mini" style="border: 0; background: transparent; box-shadow: none; padding: 0;">
        <img id="status" width="24" height="24" alt="Delete doctor" src="/Content/img/enable.png" />
    </button>
}
else
{ 
    <button id="statusDisable" class="button-enable" data-original-title="Show timetable"  data-id="@iPad.Id" data-status="true" class="btn btn-mini" style="border: 0; background: transparent; box-shadow: none; padding: 0;">
        <img id="status" width="24" height="24" alt="Delete doctor" src="/Content/img/disable.png" />
    </button>
}

【问题讨论】:

  • 你错过了最后一个括号。是这样的实际代码还是只是一个错字?
  • 这需要首先进行基本调试。它在什么时候失败 - 曾经调用过 EnableiPad() 吗?是否曾经触发过 Ajax 请求?成功回调会回来吗?控制台中是否有任何错误消息?
  • 似乎有效。可能问题出在微妙的地方。
  • 有什么错误吗?当您似乎没有使用回调中的data 时,为什么要在回调函数中处理图像更改?为什么不在post 事件之前做呢?
  • 如果选择器正常,$('#statusImg').attr("src", '/Content/img/disable.png'); 应该可以正常工作。尝试更多地调试应用程序。

标签: c# javascript jquery asp.net-mvc asp.net-mvc-3


【解决方案1】:

id 你的 img 标签是状态,所以应该是:

$('#status').attr("src", '/Content/img/disable.png');

【讨论】:

  • 在页面上我有多个具有此 ID 的图像?所以我尝试将 id 更改为 class 而不是更改选择器,但它的工作原理很奇怪,它不会改变我之前点击过的图像
  • id 必须是唯一的,因为您使用的是相同的 id,因为它不起作用,更改为 class 应该可以工作
猜你喜欢
  • 2015-09-12
  • 2023-04-07
  • 2016-12-24
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多