如何将属性对象绑定到现有元素?

时间:2012-04-29 13:37:30

标签: jquery

在jQuery中,您可以一步创建新元素并定义它们的属性:

$("<div>", {title: "Hey there!", text: "I'm a DIV!"});

这会产生:

<div title="Hey there!">I'm a DIV!</div>

有没有办法对现有元素做同样的事情?以下不起作用:

$("#theDiv", {title: "Hey there!", text: "I'm a DIV!"});

1 个答案:

答案 0 :(得分:2)

事实证明事情很容易。 jQuery使用.attr()来实现此目的。

$("#theDiv").attr({title: "Hey there!", text: "I'm a DIV!"}, true);

请注意第二个参数设置为true。这会导致jQuery使用与新创建元素相同的机制。

偶数函数参数按预期工作:

$("#theDiv").attr({
    title: "Hey there!", 
    text: function () { return "some calculated value"; }
}, true);​

See this jsFiddle.

因此,这也适用于事件绑定,CSS修改以及jQuery可以执行的所有其他操作:

$("#theDiv").attr({
    title: "Hi there", 
    text: function (i, v) { return v.replace(/not /, ""); },
    mouseover: function () { $(this).css({color: "red"}) },
    mouseout: function () { $(this).css({color: ""}) },
    css: { fontSize: "20pt", fontStyle: "italic" }
}, true);​

See this jsFiddle.

这是未记录的,所以它可以在任何点发行版中更改而不会在发行说明中列出,但似乎不太可能并且在升级时很容易测试它jQuery的。