简体   繁体   中英

JavaScript Server element onclick event

Html

<a id="lnkShowExportBtn" runat="server">Look at image</a>

jQuery

lnkShowExportBtn.Attributes.Add("onclick", @"{ var rowImage = document.getElementById('rowImage');
    if(rowImage.style.display == 'none')
           {
            rowImage.style.display = 'block';
            var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
            lnkShowExportBtn.innerHTML = 'Hide image';
          }
    else  {
            rowImage.style.display = 'none';
            var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
            lnkShowExportBtn.innerHTML = 'Look at image';
          }
}");

Get this error:

Uncaught TypeError: Cannot set property 'innerHTML' of null

What am I doing wrong? Just can't get to the point.

Thanks.

You are passing '<%=lnkShowExportBtn.ClientID%>' as a string and it is not evaluated to replace the real client id value, which you can see in the generated html. It would be a lot more simple if you add javascript in aspx and just bind it on server side.

In code behind

lnkShowExportBtn.Attributes.Add("onclick", "YourFunction()");

OR, in ASPX

<a id="lnkShowExportBtn" runat="server" onclick="YourFunction();">Look at image</a>

In javascript

function YourFunction() 
{   
  var rowImage = document.getElementById('rowImage');
  if (rowImage.style.display == 'none') {
      rowImage.style.display = 'block';
      var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
      lnkShowExportBtn.innerHTML = 'Hide image';
  } else {
      rowImage.style.display = 'none';
      var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
      lnkShowExportBtn.innerHTML = 'Look at image';
  }
}

Try this with jQuery : Here I have bind click event to lnkShowExportBtn and changing inner html of it with the help of if condition which checks of image visible. And by using .toggle() , I am making image hide and show.

$(document).ready(function(){

  $('#lnkShowExportBtn').click(function(){
       var innerHtml = 'Hide image';
       if($('.rowImage').is(':visible'))
      {
        innerHtml = 'Look at image';
      }
      $(this).html(innerHtml);
      $('.rowImage').toggle();
   });
});

Demo

For more Information on jQuery : click jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM