0 / 0 / 0
Регистрация: 25.02.2019
Сообщений: 9
1

Как справиться с ошибкой в js : Uncaught TypeError: Cannot read property 'style' of undefined

25.02.2019, 21:50. Показов 18269. Ответов 3
Метки нет (Все метки)

Не понимаю как правильно описать действия со сменой значения display :
PHP/HTML
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
<script type="text/javascript">
         elem1 = document.getElementById("window_in_main1");
         elem2 = document.getElementById("window_in_main2");
         elem3 = document.getElementById("window_in_main3");
         elem4 = document.getElementById("window_in_main4");
 
 
        function callContent_one(elem1, elem2, elem3, elem4)
            {
                if((elem2.style.display == "block") || (elem3.style.display == "block") || (elem4.style.display == "block"))
                {
                    elem2.style.display = "none";
                    elem3.style.display = "none";
                    elem4.style.display = "none";
                }
 
                elem1.style.display = "block";
            }
 
        function callContent_two(elem1, elem2, elem3, elem4)
            {
                if((elem1 == "block") || (elem3.style.display == "block") || (elem4.style.display == "block"))
                {
                    elem1.style.display = "none";
                    elem3.style.display = "none";
                    elem4.style.display = "none";
                }
 
                elem2.style.display = "block";
            }
 
        function callContent_three(elem1, elem2, elem3, elem4)
            {
                if((elem1.style.display == "block") || (elem2.style.display == "block") || (elem4.style.display == "block"))
                {
                    elem1.style.display = "none";
                    elem2.style.display = "none";
                    elem4.style.display = "none";
                }
 
                elem3.style.display = "block";
            }
 
        function callContent_four(elem1, elem2, elem3, elem4)
            {
                if((elem1.style.display == "block") || (elem2.style.display == "block") || (elem3.style.display == "block"))
                {
                    elem1.style.display = "none";
                    elem2.style.display = "none";
                    elem3.style.display = "none";
                }
 
                elem4.style.display = "block";
            }
    </script>
</head>
<body>
 
    <div id = "main_header_window"> 
    </div>
 
    <main>
        <aside>
            <ul>
                <li class="li_main_menu" onclick="callContent_one()"><a href="#" class="a_main_menu">Text 1</a></li>
                <li class="li_main_menu" onclick="callContent_two()"><a href="#" class="a_main_menu">Text 2</a></li>
                <li class="li_main_menu" onclick="callContent_three()"><a href="#" class="a_main_menu">Text 3</a></li>
                <li class="li_main_menu" onclick="callContent_four()"><a href="#" class="a_main_menu">Text 4</a></li>
            </ul>
        </aside>
        <div id="main_in_main_window">
            <div class="content_of_menu_in_main_menu one" id="window_in_main1">Text</div>
            <div class="content_of_menu_in_main_menu two" id="window_in_main2">Text</div>
            <div class="content_of_menu_in_main_menu three" id="window_in_main3">Text</div>
            <div class="content_of_menu_in_main_menu four" id="window_in_main14">Text</div>
        </div>
    </main>
 
    <div id = "main_footer_window"> 
    </div>
 
</body>
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
25.02.2019, 21:50
Ответы с готовыми решениями:

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

Uncaught TypeError: Cannot read property 'value' of undefined
Не могу понять в чем проблема выдает ошибку Uncaught TypeError: Cannot read property 'value' of...

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

Uncaught TypeError: Cannot read property 'left' of undefined
как исправить данную ошибку? и из за чего она может появляться? search.js:69 Uncaught TypeError:...

3
dev - investigator
Эксперт JSЭксперт HTML/CSS
2148 / 1493 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
26.02.2019, 04:08 2
The little nigh, ошибка у Вас происходит потому, что Вы пытаетесь обратиться к свойству объекта, которого или нет или этого свойства нет у объекта, к которому Вы обратились.
Признаюсь никакого желания исправлять Ваш код нету, простите. Предположу, что Вы хотели добиться примерно такого результата - https://jsfiddle.net/Qwerty_Wasd/fvb0kuae/
Обратите, внимание на некоторые изменения в идентификации узлов дерева.
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div id = "main_header_window"> 
</div>
 
<main>
    <aside id='aside-menu'>
        <ul>
            <li class="li_main_menu"><a href="#" class="a_main_menu">Text 1</a></li>
            <li class="li_main_menu"><a href="#" class="a_main_menu">Text 2</a></li>
            <li class="li_main_menu"><a href="#" class="a_main_menu">Text 3</a></li>
            <li class="li_main_menu"><a href="#" class="a_main_menu">Text 4</a></li>
        </ul>
    </aside>
    <div id="main_in_main_window">
        <div class="content_of_menu_in_main_menu one show" id="window_in_main1">Text 1</div>
        <div class="content_of_menu_in_main_menu two" id="window_in_main2">Text 2</div>
        <div class="content_of_menu_in_main_menu three" id="window_in_main3">Text 3</div>
        <div class="content_of_menu_in_main_menu four" id="window_in_main14">Text 4</div>
    </div>
</main>
 
<div id = "main_footer_window"> 
</div>
Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
let opAccord = {
    menu: document.getElementById('aside-menu'),
    content: document.getElementsByClassName('content_of_menu_in_main_menu'),
    events: {
        click: e => {
            if (e.target.classList.contains('a_main_menu')) {
                Array.from(opAccord.content, (el, ind) => ind === Array.from(document.getElementsByClassName(e.target.className)).indexOf(e.target) ?
                el.classList.add('show') : el.classList.remove('show'));
            }
        },
    },
}
opAccord.menu.addEventListener('click', opAccord.events.click);
Также добавлю, что то что Вы хотели сделать, если я прав конечно - это обыкновенные табы. То есть вполне можно было обойтись без JS.
Например - https://codepen.io/qwerty_wasd/pen/BGOLbW
HTML5
1
2
3
4
5
6
7
8
9
10
11
<div class="tabs-widget">
  <input class="tab-trigger" type="radio" id="tab-1-1" name="radio" checked="checked"/>
  <label for="tab-1-1">LINK1</label>
  <input class="tab-trigger" type="radio" id="tab-1-2" name="radio"/>
  <label for="tab-1-2">LINK2</label>
  <input class="tab-trigger" type="radio" id="tab-1-3" name="radio"/>
  <label for="tab-1-3">LINK3</label>
  <div class="scroller" id="tab_1_1">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi recusandae error corrupti molestias tenetur obcaecati a? Saepe magnam animi iure harum quibusdam unde sit reprehenderit accusamus dolorum, quo quis quidem?</div>
  <div class="scroller" id="tab_1_2">Loremのイプサムのニンジンは、リベートを強化します。誤って受け入れた場合面倒バウンド盲目になりますか?心の中で、これらの偉大な悲しみの一部を非難する権利、多くの場合、男性は全く不明である何の事、彼がどこから来るかで障害を見つけますか?</div>
  <div class="scroller" id="tab_1_3">Lorem ipsum गाजर बढ़ाया छूट। अगर गलती से स्वीकार कर लिया परेशानी बाध्य अंधा हो गए हैं? मन की है, है ना इन महान दु: ख में से कुछ का आरोप लगा है, अक्सर जहां वह, से आता है क्या बातें एक आदमी पूरी तरह अनजान हैं के साथ गलती खोजने के?</div>
</div>
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
*,
*:after,
*:before {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  outline: 0;
}
 
/*стили выше добавлены только для этого примера, в реальном проекте используйте normalize.css\reset.css*/
.tabs-widget {
  position: relative;
  text-align: center;
}
 
.tab-trigger {
  display: none;
}
 
label {
  margin: 0 20px;
  cursor: pointer;
}
label:hover {
  background: gray;
}
 
.scroller {
  position: absolute;
  left: 50%;
  -webkit-transform: translatex(-50%);
          transform: translatex(-50%);
  margin-top: 10px;
  width: 400px;
  opacity: 0;
  transition: 2s;
}
.scroller:nth-of-type(1) {
  color: red;
}
.scroller:nth-of-type(2) {
  color: green;
}
.scroller:nth-of-type(3) {
  color: blue;
}
 
#tab-1-1:checked ~ #tab_1_1 {
  opacity: 1;
  transition: 2s;
}
#tab-1-1:checked ~ label[for='tab-1-1'] {
  background: #000;
  color: #fff;
}
 
#tab-1-2:checked ~ #tab_1_2 {
  opacity: 1;
  transition: 2s;
}
#tab-1-2:checked ~ label[for='tab-1-2'] {
  background: #000;
  color: #fff;
}
 
#tab-1-3:checked ~ #tab_1_3 {
  opacity: 1;
  transition: 2s;
}
#tab-1-3:checked ~ label[for='tab-1-3'] {
  background: #000;
  color: #fff;
}
0
565 / 464 / 183
Регистрация: 14.10.2017
Сообщений: 1,259
26.02.2019, 08:19 3
The little nigh, можно так
Javascript
1
2
3
4
5
6
7
8
9
10
11
let mainMenu = document.querySelector('.li_main_menu').parentElement;
let mainInMainWindow = document.getElementById('main_in_main_window');
function callContent(e) {
    for(let i = 0; i < mainMenu.children.length; i++){
        if(mainMenu.children[i] == e.target.parentElement)
            mainInMainWindow.children[i].style.display = "block";
        else
            mainInMainWindow.children[i].style.display = "none";
    }
}
mainMenu.addEventListener('click', callContent);
0
Эксперт JS
2033 / 1092 / 408
Регистрация: 29.04.2016
Сообщений: 2,612
27.02.2019, 14:59 4
The little nigh,

Если речь действительно о табах то еще так можно -> https://codepen.io/Mr_Sergo/pe... itors=1000
PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<ul class="box-menu">
    <li class="menu">Text 1</li>
    <li class="menu">Text 2</li>
    <li class="menu">Text 3</li>
    <li class="menu">Text 4</li>
</ul>
<div class="content" style="display:none;">Содержимое 1</div>
<div class="content" style="display:none;">Содержимое 2</div>
<div class="content" style="display:none;">Содержимое 3</div>
<div class="content" style="display:none;">Содержимое 4</div>
 
 
<script>
    document.querySelector('.box-menu').addEventListener('click',e => {
        if(e.target.classList.contains('menu')){
            let num = [...document.querySelectorAll('.box-menu .menu')].indexOf(e.target),
                content = document.querySelectorAll('.content');
            for(let i = 0; i < content.length; i++)
                i == num ? content[i].style.display = 'block' : content[i].style.display = 'none';
        }
    });
</script>
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
27.02.2019, 14:59
Помогаю со студенческими работами здесь

Uncaught TypeError: Cannot read property 'elements' of undefined
Только начал изучать и сразу тормоз... оШИБКА: Uncaught TypeError: Cannot read property 'elements'...

Uncaught TypeError: Cannot read property 'order' of undefined
orderBy: function(event, container, element){ var id = 'id-' + this.getID(container); ...

Uncaught TypeError: Cannot read property 'top' of undefined
Добрый день, решил поставить плагин simple scroll follow.Возникает ошибка&quot;uncaught TypeError:...

Uncaught TypeError: Cannot read property 'createRange' of undefined
Вроде б все просто, но не работает function AddTags(Tag,Tag2) { document.forma.content.focus();...


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

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

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru