Passing GridView Control IDs to JavaScript

柔情痞子 提交于 2019-12-24 10:39:39

问题


I'm trying to implement a call to a Javascript function that appears within a Gridview in each row. The code produces a button that can be clicked and brings up an Image Editor instance (Aviary by Adobe).

Because I don't have unique variable names then the same image is appearing each time, if I try to do this on a standalone page and change the Javascript variable names for each image the code works so I'm not sure what to do as I don't know how to make unique variable references.

I can't include the document.getElementByID parts inline as parameters to the function because I can't escape the single quotes.

The 3 javascript variables are

editImageControl editImageURL editImageFilename

<asp:TemplateField HeaderText="Edit Photo">
    <ItemTemplate>

        <asp:Image ID="editImage" runat="server" ImageUrl='<%# "http://images.foo.com/" & Eval("filename") %>' CssClass="noDisplay" />
        <script>
            var editImageControl = document.getElementById('<%# DirectCast(Container, GridViewRow).FindControl("editImage").ClientID%>');
            var editImageURL = document.getElementById('<%# DirectCast(Container, GridViewRow).FindControl("editImage").ClientID%>').src;
            var editImageFilename = '<%# Eval("filename") %>';
        </script>

        <!-- Add an edit button, passing the HTML id of the image and the public URL of the image -->
        <p><input type='image' runat="server" src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor(editImageControl, editImageURL, editImageFilename);" /></p>

    </ItemTemplate>
</asp:TemplateField>

回答1:


When you bind editImageControl use Id instead of ClientId. Id will give you a very long and cumbersome id, but it will be unique for every element (it's the full path for the control within the page's control tree).

  var editImageControl = document.getElementById(
        '<%# DirectCast(Container, GridViewRow).FindControl("editImage").Id%>');

Another option is to set the editImage's ClientId when you define the control. This way JavaScript can access it correctly. I'm going to assume that filename is unique and is valid for storing as an html element's id (you might need to remove any path seperator or file extensions characters for this to work).

 <asp:Image ID="editImage" runat="server" ClientID='<%#Eval("filename")%>'
      ImageUrl='<%# "http://images.foo.com/" & Eval("filename") %>' 
      CssClass="noDisplay" />

Then you can use the same logic to set editImageControl:

var editImageControl = <%#Eval("filename")%>;


来源:https://stackoverflow.com/questions/27187778/passing-gridview-control-ids-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!