最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - Want to change image src of ImageButton using javascript on client click - Stack Overflow

programmeradmin1浏览0评论

I tried this first which is not working:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick="this.src='plus.gif';"/>

Another method:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick=" return changeImg(this)"/>    

 function changeImg(cnt)
    {
    if(cnt.src='minus.gif')
    {
    cnt.src='plus.gif';
    }
    else
    {
    if(cnt.src='plus.gif')
    {
    cnt.src='minus.gif';
    }
    }
    return false;
    }
    </script>

I tried this first which is not working:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick="this.src='plus.gif';"/>

Another method:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick=" return changeImg(this)"/>    

 function changeImg(cnt)
    {
    if(cnt.src='minus.gif')
    {
    cnt.src='plus.gif';
    }
    else
    {
    if(cnt.src='plus.gif')
    {
    cnt.src='minus.gif';
    }
    }
    return false;
    }
    </script>
Share Improve this question edited May 31, 2012 at 9:10 Charu asked May 31, 2012 at 6:50 CharuCharu 2,7276 gold badges36 silver badges53 bronze badges 1
  • Is it even executing the JavaScript? Quickly test by putting alert('hi'); inside the function. It might be running the JavaScript then reloading the page.... – Greg Commented May 31, 2012 at 7:24
Add a ment  | 

2 Answers 2

Reset to default 2

The issue here is that you do not return false, on client click and you trigger the onlick on code behind. Just return false; to avoid the post back and you get what you try.

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif" OnClientClick="this.src='plus.gif';return false;"/>

update

On your code you type if(cnt.src='plus.gif'), but you must type == , not =

To avoid this type of error is better to place first the const, eg type

if('plus.gif' == cnt.src)

and the final code

function changeImg(cnt)
    {
      if(endsWith(cnt.src, 'minus.gif'))
      {
        cnt.src='plus.gif';
      }
      else if(endsWith(cnt.src, 'plus.gif'))
      {
         cnt.src='minus.gif';
      }          
      // to avoid post back return false
      return false;
    }

function endsWith(str, suffix) {
   return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

relative : endsWith in JavaScript

The following should work

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="minus.gif"  onClick="function(){this.setAttribute("src", 'plus.gif');}"/>
发布评论

评论列表(0)

  1. 暂无评论