Форум программистов, компьютерный форум, киберфорум
JavaScript
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.90/29: Рейтинг темы: голосов - 29, средняя оценка - 4.90
11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150
1

Cannot read property 'addEventListener' of null

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

Author24 — интернет-сервис помощи студентам
начал изучать 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
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
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;. Это...

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

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

6
0 / 0 / 0
Регистрация: 24.06.2013
Сообщений: 5
05.01.2015, 19:32 2
походу this не так работает
0
11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150
05.01.2015, 19:36  [ТС] 3
как сделать чтобы объект правильно работал в функции ?
0
супермизантроп
Эксперт JS
3941 / 2979 / 692
Регистрация: 18.04.2012
Сообщений: 8,625
06.01.2015, 07:05 4
а где в коде определение функции CheckMapOnMines () ?
имеющееся определение функции checkMapOnMines () никак не подойдёт, ибо javascript - язык регистрозависимый
0
11 / 11 / 10
Регистрация: 10.07.2013
Сообщений: 150
06.01.2015, 21:58  [ТС] 5
Переписал 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,625
06.01.2015, 22:10 6
какой-то детсад, честное слово
то регистры путаете, то вообще объект не определяете
в строке 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  [ТС] 7
я первый раз засел за javascript
0
06.01.2015, 22:30
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
06.01.2015, 22:30
Помогаю со студенческими работами здесь

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

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

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

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


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru