所以我在论坛上四处查看,认为我已经弄明白了:
$( document ).ready(function() {
months = ['January','Februari','Mars','April','May','June','July','August','September','October','November','December'];
days = [31,28,31,30,31,30,31,31,30,31,30,31]
for(i = 1; i <= 12; i++){
$('.months').append('<div class="month" id='+i+'><p>'+months[i-1]+'</p></div>');
}
for(j = 1; j<=31; j++){
$('.days').append('<div class="numberDays"><p>'+j+'</p></div>');
}
$('.months').click(function(){
var id = this.id;
alert(id);
//$().css({'background':'red'});
});
});
计划基本上是获取点击的 div 的 id
(使用 months
类)并将其背景更改为红色而不更改其他 div 的背景颜色。但是 this.id
什么也没有返回,nada,它完全是空白的。
我还用过:
$('.months').clicked(function(){
var id = $(this).attr(id);
alert(id);
});
但是 id
最终未定义。
最佳答案
.append()
在 指定的 div 中插入内容。换句话说,您将点击事件绑定(bind)到父级 .months
,您需要将其绑定(bind)到子级:
演示:https://jsbin.com/kebisusufi/edit?html,js,output
$( document ).ready(function() {
var months = ['January','Februari','Mars','April','May','June','July','August','September','October','November','December'];
var days = [31,28,31,30,31,30,31,31,30,31,30,31];
for(i = 1; i <= 12; i++){
$('.months').append('<div class="month" id='+i+'><p>'+months[i-1]+'</p></div>');
}
for(j = 1; j<=31; j++){
$('.days').append('<div class="numberDays"><p>'+j+'</p></div>');
}
// you can also use $('.month') or any other selector
$('.months div').click(function(){
var id = this.id;
alert(id);
//$().css({'background':'red'});
});
});
关于javascript - 单击时从 div 中提取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418435/