如何将标题附加到数组中的元素?

时间:2017-10-31 14:47:16

标签: javascript jquery

如何迭代所有"选择"元素并从firstDay到第三天以正确的顺序附加标题?现在它只显示所有元素的最后一个(thirdDay)。非常感谢您的帮助!

var firstDay = "First day";
var secondDay = "Second day";
var thirdDay = "Third day";

var days = [firstDay, secondDay, thirdDay];
var select = $(".dayNumber");

for(var i=0; i<days.length; i++) {
    select.attr('title', days[i]);
}

2 个答案:

答案 0 :(得分:1)

您可以使用$.fn.each代替for loop:

var firstDay = "First day";
var secondDay = "Second day";
var thirdDay = "Third day";

var days = [firstDay, secondDay, thirdDay];
var select = $(".dayNumber");

select.each(function(index) {
  $(this).attr('title', days[index])
});

答案 1 :(得分:0)

您的循环错误,因为您没有选择特定的选择元素,您应该执行类似

的操作
for(var i=0; i<days.length; i++) {
    $(select[i]).attr('title', days[i]);
}