是否可以使用jQuery.attr()函数设置多个数据属性?

是否可以使用jQuery.attr()函数设置多个数据属性?

问题描述:

这有效:

$(myObj).attr("data-test-1", num1);
$(myObj).attr("data-test-2", num2);

但这不是:

$(myObj).attr({
  data-test-1: num1,
  data-test-2: num2
});

我在这里真的缺少明显的东西吗?

Am I missing something really obvious here?

当然,像这样:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

类似于 .attr() 文档状态:

Like the .attr() docs state:

一次设置多个属性

Setting several attributes at once

要更改alt属性并在同一位置添加title属性 时间,使用一次将名称和值集同时传递到方法中 一个普通的JavaScript对象.对象中的每个键值对相加或 修改属性:

To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a plain JavaScript object. Each key-value pair in the object adds or modifies an attribute:

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

设置多个属性时, 属性名称周围的引号是可选的.

When setting multiple attributes, the quotes around attribute names are optional.