jQuery,如何从onclick内联获取引用?

时间:2017-01-02 16:38:50

标签: javascript jquery html

有类似的东西:

<tr onclick="console.log($(this));">

我知道它很糟糕,但它是遗留代码。我想得到这个TR的参考,但是这个:

<tr onclick="console.log($(this));">

也不是这样:

<tr onclick="console.log(this);">

有效,它认为<tr onclick="事件本身。

2 个答案:

答案 0 :(得分:1)

不确定您希望tr返回什么,但它会引用$(this),如下例所示。

注意: this关键字引用jQuery对象,<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr onclick="console.log($(this).html(),this.innerHTML);"> <td>1</td> <td>2</td> <td>3</td> </tr> <tr onclick="console.log($(this).html(),this.innerHTML);"> <td>4</td> <td>5</td> <td>6</td> </tr> </table>引用它们不相同的DOM对象。

查看 What is the dollar sign in Javascript, if not jQuery 。 希望这会有所帮助。

var ref = firebase.database().ref().child('/scenes/' + projId).orderByChild('wordcount');
ref.once('value',function(snap) {
    snap.forEach(function(item) {
        var itemVal = item.val();
        keys.push(itemVal);
    });
    for (i=0; i < keys.length; i++) {
        counts.push(keys[i].wordcount);
    }   
});

答案 1 :(得分:1)

在这里区分jQuery和普通javascript非常重要。

  • $(this)是一个jQuery对象并采用jQuery方法。

  • this是一个简单的javascript关键字,采用简单的javascript方法。

示例:

&#13;
&#13;
td {
width: 100px;
height: 100px;
line-height: 100px;
font-size: 80px;
text-align: center;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
}
&#13;
<table>
<tr onclick="console.log(this.innerHTML);">
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</table>
&#13;
&#13;
&#13;