简体   繁体   English

为什么我的divs值未定义?

[英]Why would my divs value be undefined?

I'm creating global div elements and assigning them all a value to represent their day of the week. 我正在创建全局div元素,并为它们分配一个值来代表它们的星期几。

var daysOfWeek = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
var daysOfWeekNum = [1,2,3,4,5,6,0]

var dayOfWeek = myDiv.append('div')
    .classed('dayOfWeek', true)

var dayLabels = daysOfWeek.forEach(function(DoW, DoWN){
   dayOfWeek.append('div')
        .attr("value", function(){ return parseInt((DoW == 'Sun') ? DoWN = 0 : DoWN = DoWN + 1)})
        .text(DoW)
})

Then later on down in the script, I run this. 然后在脚本中继续运行。

d3.selectAll('div.dayOfWeek')
    .on('click', function(){
        console.log(this)
        console.log(this.value)
    })

So when I run console.log(this) the output looks like this: 因此,当我运行console.log(this) ,输出如下所示:

<div class = "dayOfWeek" value="4">Thurs</div>

My problem is in the console.log(this.value) . 我的问题是在console.log(this.value) I don't get a value when I try to log it. 尝试记录时没有值。 It just gives me undefined . 它只是给我undefined Am I missing something obvious? 我是否缺少明显的东西?

Divs don't have a value attribute in HTML, and the value property doesn't map on to the non-existent attribute in the DOM. Divs在HTML中没有value属性,并且value属性不会映射到DOM中不存在的属性。

If you set the attribute, then you have to read the attribute to get the data base. 如果设置了属性,则必须读取属性以获取数据库。

Since divs don't have a value attribute, you shouldn't be setting one though. 由于div没有值属性,因此您不应设置一个。 Use data-* attributes if you want to add custom data to an element. 如果要将自定义数据添加到元素,请使用data-*属性。

 document.querySelector('div').dataset.value = 1234; alert(document.querySelector('div').dataset.value); 
 <div>My div</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM