【问题标题】:Quickest way to find an element with jQuery使用 jQuery 查找元素的最快方法
【发布时间】:2009-10-29 06:43:10
【问题描述】:

给定以下 html:

<tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
        <td><img id="imgProductPurchased" runat="server" visible="true" alt="Product Purchased" title="Product Purchased" src="/sitecore/shell/Themes/Standard/Applications/16x16/checkbox.png" /></td>
        <td>
            <asp:PlaceHolder ID="plhPurchased" runat="server">
                <span class="roundButton roundButtonLarge"><a id="hypPurchased" class="registryPurchased" href="#" title="Mark product as purchased" runat="server"><span>
                <em class="registryPurchased"></em>Purchased</span></a> <span class="buttonEndLarge">
                </span></span>
            </asp:PlaceHolder>
        </td>
    </tr>
            <tr>
                    Repeats above
            </tr>

我在“hypPurchased”上有一个点击事件。当该事件触发时,我需要访问该行的 plhPurchased 元素和“imgProductPurchased”元素。

编辑:

我应该说这是使用 ASP.NET 构建的,因此,id 都是唯一的。

【问题讨论】:

  • 鉴于它是一个 ASP.NET 占位符,在呈现的 HTML 中是否存在 ID 为 plhPurchased 的元素?当您在浏览器中查看源代码时,这是什么样的?

标签: javascript jquery jquery-selectors


【解决方案1】:

如果点击事件在特定的行上并且元素是该行的子元素,您可以使用上下文来获取结果。

$(".myRow").click(function() {
    var somethingFromMyRow = $(".myChildClassName", this).text();
    alert(somethingFromMyRow);
});

请注意,您不应该在页面上的任何地方复制相同的 ID,因此我提供的示例使用了类名 - 所以假设您的示例中有这样的 HTML。

<tr class="myRow">
    <td><span class="myChildClassName">Some Text In Row 1</span></td>
    <td>More Stuff</td>
</tr>
<tr class="myRow">
    <td><span class="myChildClassName">Some Text In Row 2</span></td>
    <td>More Stuff</td>
</tr>
<tr class="myRow">
    <td><span class="myChildClassName">Some Text In Row 3</span></td>
    <td>More Stuff</td>
</tr>

【讨论】:

    【解决方案2】:

    id's 不能在 HTML 中复制,

    无论如何,您需要做的是获取父元素(在层次结构中向上,直到获取包含“当前”行的父元素),然后针对它运行查询:

    jQuery( your_query_string, parent )
    

    parent 是你可以使用的东西:

    parent = query.parent()
    

    例如:

    function click_handler(element)
    {
        parent = jQuery(element).parent()
        name = jQuery(".name", parent)
        // do stuff
    }
    

    name = jQuery(".name", parent) 将获取parent 元素下所有具有name 类的元素。

    【讨论】:

      【解决方案3】:

      Hasen 说过,你不能在 html 中复制 id。

      所以,将一个类应用于“plhPurchased”,然后:

      在 hypPurchased 中,您将 onclick="yourFuntion(this)"

      function yourFuntion(elem)
      {
        var tr=$(elem).closest('tr');
        var _imgProductPurchased = tr.find('img');
        // if you have more then a img per row, you should apply a class to the image to and get it by:
        // tr.find('.imgClass');
        var _plhPurchased=tr.find('.thatClassYouApplyed');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-07
        • 1970-01-01
        • 2010-09-29
        • 2018-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多