11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150

Cannot read property 'addEventListener' of null

05.01.2015, 18:42. Показов 6024. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
начал изучать javascript html

делаю Сапёра на html/javascript/css
не пойму в чем проблемма
chromовский отладчик пишет что
Cannot read property 'addEventListener' of null
на 68-70 строке в файле js
код html
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="Mines.css">
<script src="Mines.js"></script>
   <head>
    
    <meta charset="UTF-8">
    <title>сапер</title>
</head>
<body>
   <div>
    <script>
         SetMap();
          Mines();
CheckMapOnMines();
 
    </script>
        <button id="Flag" class="score">
        <script>
        document.write("<pre>"+CountOfMines+"мин\n" +
                        CountFlags+"флагов"+"</pre>");
        </script>
        </button>
    </div>
    
    
</body>
</html>
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var CountOfMines=0;   // количество мин
var Flag=false;     // переключатель между флажком и нажатием
var Column = 10;    // строки
var Lines = 10;     // столбцы
var CountMines = 10;
var CountFlags = CountMines;// количество флажков
// мины
var Flags = Array(Column);//флажки
//количество мин поблизости
var Element;
var checkMapOnMines = function()
{
    
for (var i =0;i<Column;i++)
{
     for (var j=0;j<Lines;j++)
     {
        if((i>0)       && (j>0)        && Element[i-1][j-1].Mine == true){Element[i][j].CountOfMines++;}
        if((j>0)                       && Element[ i ][j-1].Mine == true){Element[i][j].CountOfMines++;}
        if((i<Column-1)&& (j>0)        && Element[i+1][j-1].Mine == true){Element[i][j].CountOfMines++;}
        if((i>0)                       && Element[i-1][ j ].Mine == true){Element[i][j].CountOfMines++;}
        if((i<Column-1)                && Element[i+1][ j ].Mine == true){Element[i][j].CountOfMines++;}
        if((i>0)       && (j<Lines-1)  && Element[i-1][j+1].Mine == true){Element[i][j].CountOfMines++;}
        if((j<Lines-1)                 && Element[ i ][j+1].Mine == true){Element[i][j].CountOfMines++;}
        if((i<Column-1)&& (j<Lines-1)  && Element[i+1][j+1].Mine == true){Element[i][j].CountOfMines++;}
     }
} 
 
  
}
 
var Mines = function(){
 while(CountOfMines!=CountMines)
    {
    var int1 = getRandomInt(0,Lines-1);
    var int2 = getRandomInt(0,Column-1);
        if(Element[int1][int2].Mine == 1)
        {
        int1 = getRandomInt(0,Lines-1);
        int2 = getRandomInt(0,Column-1);
        }
        document.getElementById("b"+int1+int2).className+="clicked";
        Element[int1][int2].Mine = 1;
        
        CountOfMines++;
    }
}
 
var SetMap = function (){
    for (var i = 0;i<Column;i++)
{ 
    Element[i] =[];
for (var j = 0;j<Lines;j++){
    Element[i][j] = {}
    }
    }
    
    CountOfMines =0; 
for (var i = 0;i<Column;i++){   
    for (var j = 0;j<Lines;j++){
        Element[i][j] = new Object();
        Element[i][j].CountOfMines = 0;
        Element[i][j].Mine =0;
        Element[i][j]._i = i;
        Element[i][j]._j = j;
Element[i][j].ClickButton = function(){if(this.Mine ==1){alert("вы проиграли");}console.log( this.Mine);}
document.write("<button id=\"b"+i+j+"\>"+"</button>");  
        if(window.addEventListener){
document.getElementById("b"+i+j).addEventListener("click",Element[i][j].ClickButton(),false);}
        else if(window.attachEvent)
        document.getElementById("b"+i+j).attachEvent("onclick",Element[i][j].ClickButton());
    
           
       }
 
    
    
    }
}
 
var getRandomInt = function(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
                                 }
                                 
 
//////////////////////////////////////////////////////////////////////////////////////////
 
 
 
 
 
 
 
/////////////////////////////////////////////////////////////////////////////////////////
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
*
{
transition : .1s;
    padding:0px;
    margin:0px;
 ;
}
 
body
{
    height:100%px;
    width: 1280px;
    display:inline-block;
    background-color:#008d00;
    
}
div
{
  
 width:400px;
    height:400px;
    margin-left:auto;
    margin-right:auto;
}
 
button
{
width:40px;
height:40px;
margin:0px;
background-color:#4c50aa;
border-style:dashed;
margin:0px auto;
float:left;
    box-shadow:0 0 0 5px rgba(0,0,0,0.4);
}
.clicked
{
background-color:#ff0000;
}
.mines
{
background-color:#00be00;
    font:"PT Sans",Sans-Serif;
 
}
button:hover
{ 
    background-color:#fff;
}
button:active
{
 
    box-shadow:0px 0px 0px 0px rgb(128, 59, 0);
 
 
}
 
 
.score
{   text-align:center;
    
    width:400px;
    height:100px;
    margin:20px 0 0 0;
    background:#c13b00;
    border-color:white;
    box-shadow:0px 20px 0px 0px rgb(128, 59, 0);
    border-radius:5%;
}
button.score
{
text-align:center;
    
    width:100px;
    height:100px;
    margin:20px 0 0 0;
    background:#c13b00;
    border-color:white;
    box-shadow:0px 20px 0px 0px rgb(128, 59, 0);
    border-radius:50%;
    border-style:none;
    
}
button.score:active
{
-webkit-transform:translate(0,20px);
    box-shadow:0px 0px 0px 0px rgb(128, 59, 0);
 
 
}
Добавлено через 1 час 15 минут
без ошибок теперь но только функция
JavaScript
1
2
3
4
5
6
7
8
Element[i][j].ClickButton = function()
{
if(this.Mine == 1)
{
alert("вы проиграли");
}
console.log(this.CountOfMines);
}
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
///////////////////////////////////////////////////////////////////////////
var CountOfMines=0;   // количество мин
var Flag=false;     // переключатель между флажком и нажатием
var Column = 10;    // строки
var Lines = 10;     // столбцы
var CountMines = 10;// количество мин
var CountFlags = CountMines;// количество флажков
// мины
var Flags = Array(Column);//флажки
//количество мин поблизости
var Element = [];
var checkMapOnMines = function()
{
    
for (var i =0;i<Column;i++)
{
     for (var j=0;j<Lines;j++)
     {
        if((i>0)       && (j>0)        && Element[i-1][j-1].Mine == true){Element[i][j].CountOfMines++;}
        if((j>0)                       && Element[ i ][j-1].Mine == true){Element[i][j].CountOfMines++;}
        if((i<Column-1)&& (j>0)        && Element[i+1][j-1].Mine == true){Element[i][j].CountOfMines++;}
        if((i>0)                       && Element[i-1][ j ].Mine == true){Element[i][j].CountOfMines++;}
        if((i<Column-1)                && Element[i+1][ j ].Mine == true){Element[i][j].CountOfMines++;}
        if((i>0)       && (j<Lines-1)  && Element[i-1][j+1].Mine == true){Element[i][j].CountOfMines++;}
        if((j<Lines-1)                 && Element[ i ][j+1].Mine == true){Element[i][j].CountOfMines++;}
        if((i<Column-1)&& (j<Lines-1)  && Element[i+1][j+1].Mine == true){Element[i][j].CountOfMines++;}
     }
} 
 
    for (var i =0;i<Column;i++)
{
     for (var j=0;j<Lines;j++)
     {
       document.getElementById("b"+i+j).innerHTML = Element[i][j].CountOfMines;
             }}
}
 
var Mines = function(){
 while(CountOfMines!=CountMines)
    {
    var int1 = getRandomInt(0,Lines-1);
    var int2 = getRandomInt(0,Column-1);
        if(Element[int1][int2].Mine == 1)
        {
        int1 = getRandomInt(0,Lines-1);
        int2 = getRandomInt(0,Column-1);
        }
        document.getElementById("b"+int1+int2).className+="clicked";
        Element[int1][int2].Mine = 1;
        CountOfMines++;
    }
}
 
var SetMap = function (){
    for (var i = 0;i<Column;i++)
{ 
    Element[i] =[];
for (var j = 0;j<Lines;j++){
    Element[i][j] = {}
    }
    }
    
    CountOfMines =0; 
for (var i = 0;i<Column;i++){   
    for (var j = 0;j<Lines;j++){
        Element[i][j] = new Object();
        Element[i][j].CountOfMines = 0;
        Element[i][j].Mine =0;
        Element[i][j]._i = i;
        Element[i][j]._j = j;
Element[i][j].ClickButton = function()
{
if(this.Mine == 1)
{
alert("вы проиграли");
}
console.log(this.CountOfMines);
}
    
       
       
document.write("<button id=\"b"+i+j+"\">"+"</button>");  
    document.getElementById("b"+i+j).addEventListener("click",Element[i][j].ClickButton,false);
    
    
    }
    
    }
}
var getRandomInt = function(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
                                 }
                                 
 
//////////////////////////////////////////////////////////////////////////////////////////
 
 
 
 
 
 
 
/////////////////////////////////////////////////////////////////////////////////////////
Добавлено через 13 минут
но только функция
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
Element[i][j].ClickButton = function()
{
if(this.Mine == 1)
{
alert("вы проиграли");
}
console.log(this.CountOfMines);
}
пишет в консоли undefined
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
05.01.2015, 18:42
Ответы с готовыми решениями:

Uncaught TypeError: Cannot read property 'addEventListener' of null
Приветствую всех, такая проблема: Пишу небольшой калькулятор стоимости определённого продукта. На первой странице висят обработчики на...

Cannot read property childnodes of null
Отладчик браузера ругается на &quot;childNodes&quot;. Пишет &quot;cannot read property childnodes of null&quot;. Это User.JS скрипт, если что. Как исправить?...

Cannot read property 'style' of null
Здравствуйте! Вашему вниманию код, который работал до того момента как я решил добавить кое-какие скрипты, которые затем удалил. Казалось...

6
0 / 0 / 0
Регистрация: 24.06.2013
Сообщений: 5
05.01.2015, 19:32
походу this не так работает
0
11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150
05.01.2015, 19:36  [ТС]
как сделать чтобы объект правильно работал в функции ?
0
супермизантроп
Эксперт JS
3941 / 2979 / 692
Регистрация: 18.04.2012
Сообщений: 8,629
06.01.2015, 07:05
а где в коде определение функции CheckMapOnMines () ?
имеющееся определение функции checkMapOnMines () никак не подойдёт, ибо javascript - язык регистрозависимый
0
11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150
06.01.2015, 21:58  [ТС]
Переписал js под классы
не могу понять почему у меня Button_Mine.prototype.click возвращает

undefined
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
function getRandomInt(min, max)
{ return Math.floor(Math.random() * (max - min + 1)) + min;   }
 
    
function map(cols,lines,CountOfMines)
{
this.CountOfMines = CountOfMines;
this.Cols  = cols;
this.Lines = lines; 
this.Element = [];
for (var i  =0;i<this.Cols;i++)
{this.Element[i] =[];
 for (var j = 0;j<this.Lines;j++)
    {
    this.Element[i][j] = new Button_Mine(0,0);
}
    }
    console.log(this.Cols);
}
map.prototype.Create = function()
{
for (var i = 0;i<this.Cols;i++){for (var j =0;j<this.Lines;j++){
  document.write("<button id=\"b"+i+j+"\">"+"</button>");
this.Element[i][j].link = document.getElementById("b"+i+j);
    this.Element[i][j].link.addEventListener("click",this.Element[i][j].click,"false");
  
 
}}}
map.prototype.SetMines = function()
{
var i = 0;
      var int1 , int2;
    console.log("CountOfMines = " + this.CountOfMines);
    while(i <=this.CountOfMines)
    {
        
       int1 = getRandomInt(0,(this.Cols)-1);
       int2 = getRandomInt(0,(this.Lines)-1);
  if(this.Element[int1][int2].Mine==1)
  {
      int1 = getRandomInt(0,(this.Cols)-1);
      int2 = getRandomInt(0,(this.Lines)-1);
  }
        console.log(this.Cols+" "+int1+" "+int2);
    console.log(this.Lines);
        this.Element[int1][int2].Mine = 1;
        this.Element[int1][int2].link.style.backgroundColor="red";
   i++;
    }
 
 
 
}
map.prototype.CheckCountOfMines = function()
{
    for (var i = 0;i<this.Cols;i++)
    {
    for (var j = 0;j<this.Lines;j++)
    {
    
        if((i>0)       && (j>0)                && this.Element[i-1][j-1].Mine == true){this.Element[i][j].CountOfMines++;}
        if((j>0)                               && this.Element[ i ][j-1].Mine == true){this.Element[i][j].CountOfMines++;}
        if((i<this.Cols-1)&& (j>0)             && this.Element[i+1][j-1].Mine == true){this.Element[i][j].CountOfMines++;}
        if((i>0)                               && this.Element[i-1][ j ].Mine == true){this.Element[i][j].CountOfMines++;}
        if((i<this.Cols-1)                     && this.Element[i+1][ j ].Mine == true){this.Element[i][j].CountOfMines++;}
        if((i>0)       && (j<this.Lines-1)     && this.Element[i-1][j+1].Mine == true){this.Element[i][j].CountOfMines++;}
        if((j<this.Lines-1)                    && this.Element[ i ][j+1].Mine == true){this.Element[i][j].CountOfMines++;}
        if((i<this.Cols-1)&& (j<this.Lines-1)  && this.Element[i+1][j+1].Mine == true){this.Element[i][j].CountOfMines++;}
       }
}
        console.log(this.Cols);
}
 
var Map = new map(10,10,10);
Map.Create();
Map.SetMines();
Map.CheckCountOfMines();
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="Mines.css">
 
   <head>
    
    <meta charset="UTF-8">
    <title>сапер</title>
</head>
<body>
   
 <div>
<header>
</header>
 <script src="Mines2.js"></script>
   
    
    </div>
   
    </body>
</html>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
*
{
transition : .1s;
    padding:0px;
    margin:0px;
 ;
}
 
body
{
    display:block;
   background-color:#ddac29;
    margin:auto;
}
div
{
    margin-top:100px;
    
    margin-bottom:auto;
   
    margin-left:auto;
    margin-right:auto;
    width:400px;
    height:400px;
    box-shadow:1px 1px 20px 10px #3d4083;
    max-width:400px;
    max-height:400px;
    border-radius:1%;
}
div.itemsforgame
{
    
width:200px;
    height:200px;
    background:#fff;
    border-radius:50%;
    margin-left:50%;
    margin-right:50%;
    margin-bottom:50%;
    box-shadow:00px 00px px 20px rgba(0,0,0,.4);
}
 
button
{
width:40px;
height:40px;
margin:0px;
background-color:#4c50aa;
 
margin:0px auto;
float:left;
    border-radius:1%;
 
}
.clicked
{
background-color:#ff0000;
background:url('%D0%91%D0%B5%D0%B7%D1%8B%D0%BC%D1%8F%D0%BD%D0%BD%D1%8B%D0%B9.gif') center ;
}
.mines
{
background-color:#00be00;
 
 
}
button:hover
{ 
    background-color:#fff;
}
button:active
{
 
    box-shadow:0px 0px 0px 0px rgb(128, 59, 0);
 
 
}
 
 
.score
{   text-align:center;
    
    width:400px;
    height:100px;
    margin:20px 0 0 0;
    background:#c13b00;
    border-color:white;
    box-shadow:0px 20px 0px 0px rgb(128, 59, 0);
    border-radius:5%;
}
button.score
{
text-align:center;
    
    width:100px;
    height:100px;
    margin:20px 0 0 0;
    background:#c13b00;
    border-color:white;
    box-shadow:0px 20px 0px 0px rgb(128, 59, 0);
    border-radius:50%;
    border-style:none;
    
}
button.score:active
{
-webkit-transform:translate(0,20px);
    box-shadow:0px 0px 0px 0px rgb(128, 59, 0);
 
 
}
Добавлено через 4 часа 3 минуты
не могу понять почему не работает
0
супермизантроп
Эксперт JS
3941 / 2979 / 692
Регистрация: 18.04.2012
Сообщений: 8,629
06.01.2015, 22:10
какой-то детсад, честное слово
то регистры путаете, то вообще объект не определяете
в строке this.Element[i][j] = new Button_Mine(0,0); с тем же успехом можете написать this.Element[i][j] = new HrenVamVsem(0,0);

неряшливость в программировании недопустима... если не можете её в себе побороть, тогда программирование - не ваше дело
мей би, вам следует чем иным заняться... коров, например, пасти
ничего личного - все профессии нужны
0
11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150
06.01.2015, 22:30  [ТС]
я первый раз засел за javascript
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
06.01.2015, 22:30
Помогаю со студенческими работами здесь

TypeError: Cannot read property 'style' of null
Уважаемые! У меня проблема. Никак не могу привыкнуть к странностям JS. Вот код и почему-то он не хочет работать. var w=screen.width; ...

Uncaught TypeError: Cannot read property 'className' of null
var ex = document.getElementById(&quot;exchanges&quot;); var end = document.getElementById(&quot;end&quot;); var re = document.getElementById(&quot;request&quot;); ...

Uncaught TypeError: Cannot read property 'style' of null
Доброго времени суток! Есть список, и две кнопки, по нажатию на одну из них список уезжает влево и прозрачность становится 0, при нажатии...

Не применяются свойства - Uncaught TypeError: Cannot read property 'style' of null
Приветствую всех. document.body.style.backgroundColor = 'red'; Вот есть код , когда запускаю его , то в консоли пишет Uncaught...

Ошибка с присвоением элементу стиля Cannot read property 'style' of null"
я наверное чего-то о яваскрипт не знаю, но у меня не работает вот этот скриптvar workDone = 15;...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

Новые блоги и статьи
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Первый деплой
lagorue 17.01.2026
Не спеша развернул своё 1ое приложение в kubernetes. А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Изучаю kubernetes
lagorue 14.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru