如何使用 jQuery 在使用时返回表行元素"this?"



我正在使用ASP.NET列表视图控件,其中我正在构建表元素。

<asp:ListView ID="ListView1" runat="server">
    <LayoutTemplate>
        <table>
            <tr class="header">
                <td></td>
            </tr>
            <tr id="itemPlaceHolder runat="server">
        </table>
    </LayoutTemplate>
    <ItemTemplate>
        <tr onclick="RowClick();">
    </ItemTemplate>
</asp:ListView>

我正在调用"单击行"后面的JavaScript功能。

function RowClick() {
    var tds = $(this).children('td');
}

我的问题是我的RowClick()函数中的$(this)不返回tr元素,而是返回整个窗口。我该如何实现?我是否正在处理情况?这是不可能的,我正在追逐鬼吗?谢谢!原谅我的标记,仍然还没有完全掌握。

您需要传递处理程序invokation的自定义执行上下文,您使用function.call()执行此

<tr onclick="RowClick.call(this);">

使用jQuery?嗯,让我看看。

jQuery("tr").click(RowClick);

问候。

在处理代码方面,这不是非常" jQuery'Sque"。更"适当的"方法是做这样的事情:

<tr class="row-click">

和您的JavaScript:

$(function(){
    $(".row-click").each(function(){
        $(this).on("click",function(){
            var tds = $(this).children('td');
            //Code goes here...
        });
    });
});

另外,如果要保留" RowClick"功能,则可以执行:

$(function(){
    $(".row-click").each(function(){
        $(this).on("click",function(){
            RowClick($(this));
        });
    }
});
function RowClick(element){
    var tds = $(element).children('td');
    //Code goes here...
}

我强烈建议不要用JS呼叫和jQuery弄乱您的html,然后将其处理得很漂亮:

$(document).ready(function(){
    // create the function
    function RowClick(target){
        var tds = target.children('td');
        // another option :)
        var tds = target.find('td');
    }
    // listen for a <tr> to get clicked within the <table> -> <ItemTemplate> combo and pass the <tr> target to the function
    $('table ItemTemplate').on('click', 'tr', function(){
        RowClick($(this));
    });
});

最新更新