【问题标题】:JQuery .on() method not working with image clickJQuery .on() 方法不适用于图像点击
【发布时间】:2017-05-24 14:08:05
【问题描述】:

我正在尝试实现具有展开/折叠功能的嵌套网格视图。我的问题是 jQuery 点击功能不起作用。场景如下:

jQuery:

$("[src*=plus]").on("click", "img", function () {
            alert('hi');
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "images/minus.png");
        });
        $("[src*=minus]").on("click", "img", function () {
            $(this).attr("src", "images/plus.png");
            $(this).closest("tr").next().remove();
        });

网格视图:

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
        DataKeyNames="Id" OnRowDataBound="OnRowDataBound">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <img alt = "" style="cursor: pointer" src="images/plus.png" />
                    <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
                        <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false">
                            <Columns>
                                <asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Order Id" />
                                <asp:BoundField ItemStyle-Width="150px" DataField="Policy" HeaderText="Date" />
                            </Columns>
                        </asp:GridView>
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Contact Name" />
            <asp:BoundField ItemStyle-Width="150px" DataField="Name" HeaderText="City" />
        </Columns>
    </asp:GridView>

现在,如果我用 .live() 方法更改 .on() 方法,那么它工作得很好。任何精通 jQuery 的人都知道我做错了什么。谢谢!

【问题讨论】:

    标签: jquery asp.net gridview


    【解决方案1】:

    很遗憾,您没有正确使用.on()

    $("[src*=plus]").on("click", "img", function () {
    

    这行意味着它正在寻找&lt;img&gt;标签作为选择器$("[src*=plus]")的子标签

    由于您的图像元素是这样写的&lt;img alt = "" style="cursor: pointer" src="images/plus.png" /&gt;,您有两个选择;

    1) 如果您的&lt;img&gt; 在代码执行时已经存在,您可以简单地使用

    $("img[src*=plus]").on("click", function () {
    

    2) 如果您的 &lt;img&gt; 是动态创建的(例如 dom 注入),您需要指定一个已经存在的选择器。像这样的:

    $("body).on("click", "img[src*=plus]", function () {
    

    【讨论】:

    • 太棒了!谢谢你的知识。因此,就我而言,为了使其正常工作,我必须将代码放在$(document).ready(function () { 之间。现在我的问题是它不会触发$("img[src*=minus]").on("click", function () { 函数。相反,它重新进入$("img[src*=plus]").on("click", function () { 并不断扩大......有什么想法吗?
    • 好的;所以我设法通过向图像添加一个 id 标签并通过它的 id 来引用它来解决这个问题。非常感谢您的帮助。
    • @Dev Ngron - 我也面临同样的问题。您能否发布一些有关如何解决该问题的示例代码
    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多