jQuery:如何引用正在操作的元素?

时间:2010-02-26 15:19:22

标签: jquery

假设我有以下jQuery行,我试图在克隆表行后更改元素的“id”。如何引用元素的实例并将其传递给“buildControlId”函数。

$row.find("select [id$='ctlType']").attr("id", buildControlId(???));

我可以这样做,但我正在寻找更短版本,而无需声明变量。

var $el = $row.find("select [id$='ctlType']");
$el.attr("id", buildControlId($el[0]));

2 个答案:

答案 0 :(得分:1)

$row.find("select [id$='ctlType']").each(function() {
   $(this).attr("id", buildControlId(this));
});

这种方式还具有处理多个元素的优点。考虑更改选择器以选择多个元素(如果这是有意义的)。

答案 1 :(得分:1)

您可以指定一个函数作为第二个参数:

$row.find("select [id$='ctlType']").attr("id", function(){
    buildControlId($(this));
});

您的函数将返回属性的值:

function buildControlId($param){
    return "hello";
}