我可以使用此关键字引用jQuery链中的对象吗?

时间:2014-04-24 10:46:21

标签: jquery

假设我需要在<p>标记中增加一个数字字符。可以使用下面这样的东西吗?

$('p').text(parseInt("THIS") + 1);

当我执行以下操作时,this似乎不是指同一个对象:

$('p').text($(this).height()); //prints 731
$('p').text($(this).text()); //changes to blank

1 个答案:

答案 0 :(得分:3)

是的,但您必须使用匿名函数:

$('p').text(function(i, t) {
    // i is the index of the element amongst the collection,
    // t is the text if the element.
    // assuming that the first text-character is a valid number:
    return parseInt(t, 10) + 1;
});