Форум программистов, компьютерный форум, киберфорум
jQuery
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.71/7: Рейтинг темы: голосов - 7, средняя оценка - 4.71
1 / 1 / 1
Регистрация: 15.10.2019
Сообщений: 54

Почему не работает событие по клику?

25.12.2019, 16:58. Показов 1493. Ответов 6

Студворк — интернет-сервис помощи студентам
Привет

Не могу понять, почему не работают события на элементах, которые я вставляю в страницу через JS?

Вот пример. Сверху то, что сразу есть в HTML. Как видим, по клику всё работает, как надо. А снизу то, что я вставляю через JS. И клики не отрабатываются.

https://codepen.io/AnnNachalova/pen/bGNRrvN

Кликните здесь для просмотра всего текста
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<div class="container">
  <div class="nf-subscribe">
    <div class="row pt-4 subscribe-pay-method-box">
      <div class="col-12">
        <div class="main-title-pay">
          Выбирите способ оплаты:
        </div>
      </div>
      <div class="col-12 col-lg-6">
        <label for="pay-method-1" class="label-subscribe-pay-method">
          <input type="radio" name="subscribe-pay-method" id="pay-method-1" value="1" />
          <div class="content-box">
            <div class="dot"></div>
            <div class="title-box">
              <div class="title">Онлайн</div>
            </div>
          </div>
        </label>
      </div>
      <div class="col-12 col-lg-6">
        <label for="pay-method-2" class="label-subscribe-pay-method">
          <input type="radio" name="subscribe-pay-method" id="pay-method-2" value="2" />
          <div class="content-box">
            <div class="dot"></div>
            <div class="title-box">
              <div class="title">Наличными</div>
            </div>
          </div>
        </label>
      </div>
    </div>
  </div>
</div>
<hr>
<div class="container">
  <div class="nf-subscribe">
    <div class="row pt-4 subscribe-pay-method-box">
      <div class="col-12">
        <div class="main-title-pay">
          Выбирите способ оплаты:
        </div>
      </div>
      <div class="col-12">
        <div class="row" id="chkpay">
          <!-- вставляю через JS -->
        </div>
      </div>
    </div>
  </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
74
75
76
77
78
79
80
81
82
.nf-subscribe .subscribe-pay-method-box .main-title-pay {
  font-weight: bold;
  font-size: 16px;
  color: #2C2C2C;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method {
  display: block;
  -webkit-box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
          box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
  border-radius: 4px;
  padding: 0;
  margin: 0;
  cursor: pointer;
  background: #ffffff;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method:hover {
  -webkit-box-shadow: inset 2px 0 0 #004FC5, inset 0 2px 0 #004FC5, inset 0 -2px 0 #004FC5, inset -2px 0 0 #004FC5;
          box-shadow: inset 2px 0 0 #004FC5, inset 0 2px 0 #004FC5, inset 0 -2px 0 #004FC5, inset -2px 0 0 #004FC5;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .content-box {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
      -ms-flex-direction: row;
          flex-direction: row;
  padding: 11px 15px;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .dot {
  position: absolute;
  display: block;
  width: 12px;
  height: 12px;
  background: #ffffff;
  border-radius: 50%;
  border: 1px solid #004FC5;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .title-box {
  padding-left: 25px;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .title-box .title {
  color: #444444;
  font-size: 16px;
  line-height: 24px;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .title-box .subtitle {
  font-size: 13px;
  line-height: 18px;
  color: #444444;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method input {
  display: none;
}
 
.nf-subscribe .subscribe-pay-method-box .selected {
  background-color: #E2E4E6;
  -webkit-box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
          box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
}
 
.nf-subscribe .subscribe-pay-method-box .selected:hover {
  -webkit-box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
          box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
}
 
.nf-subscribe .subscribe-pay-method-box .selected .dot {
  background: #004FC5;
  -webkit-box-shadow: inset 2px 0 0 #ffffff, inset 0 2px 0 #ffffff, inset 0 -2px 0 #ffffff, inset -2px 0 0 #ffffff;
          box-shadow: inset 2px 0 0 #ffffff, inset 0 2px 0 #ffffff, inset 0 -2px 0 #ffffff, inset -2px 0 0 #ffffff;
}
JavaScript
1
2
3
4
5
6
7
8
9
10
$(document).ready(function() {
  $(".nf-subscribe .subscribe-pay-method-box input[name=subscribe-pay-method]").change(function() {
    $(".label-subscribe-pay-method").removeClass("selected");
    $(this).parent().addClass("selected");
  });
  
  var chkpayElement = $('#chkpay');
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-3" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-3" value="3"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Онлайн</div></div></div></label></div>'));
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-4" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-4" value="4"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Наличные</div></div></div></label></div>'));
});
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
25.12.2019, 16:58
Ответы с готовыми решениями:

Событие по клику
Здравствуйте Уважаемые форумчане и гуру форума , я новичок в программировании поэтому прошу сильно не пинать, у меня такой вопрос, открытие...

Событие по клику
Доброго времени суток. На данный момент изучаю javascript, и вот возникло нечто таоке. Событие по клику. Прилагаю код. Он не работает....

Событие только по первому клику
Всем привет. Ребят, возник такой вопрос: А как делают на часто посещаемых сайтах, к примеру, с онлайн фильмами или скачиванием чего-то...

6
1 / 1 / 1
Регистрация: 15.10.2019
Сообщений: 54
25.12.2019, 17:35  [ТС]
Привет

Не могу понять, почему не работают события на элементах, которые я вставляю в страницу через JS?

Вот пример. Сверху то, что сразу есть в HTML. Как видим, по клику всё работает, как надо. А снизу то, что я вставляю через JS. И клики не отрабатываются.

https://codepen.io/AnnNachalova/pen/bGNRrvN

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<div class="container">
  <div class="nf-subscribe">
    <div class="row pt-4 subscribe-pay-method-box">
      <div class="col-12">
        <div class="main-title-pay">
          Выбирите способ оплаты:
        </div>
      </div>
      <div class="col-12 col-lg-6">
        <label for="pay-method-1" class="label-subscribe-pay-method">
          <input type="radio" name="subscribe-pay-method" id="pay-method-1" value="1" />
          <div class="content-box">
            <div class="dot"></div>
            <div class="title-box">
              <div class="title">Онлайн</div>
            </div>
          </div>
        </label>
      </div>
      <div class="col-12 col-lg-6">
        <label for="pay-method-2" class="label-subscribe-pay-method">
          <input type="radio" name="subscribe-pay-method" id="pay-method-2" value="2" />
          <div class="content-box">
            <div class="dot"></div>
            <div class="title-box">
              <div class="title">Наличными</div>
            </div>
          </div>
        </label>
      </div>
    </div>
  </div>
</div>
<hr>
<div class="container">
  <div class="nf-subscribe">
    <div class="row pt-4 subscribe-pay-method-box">
      <div class="col-12">
        <div class="main-title-pay">
          Выбирите способ оплаты:
        </div>
      </div>
      <div class="col-12">
        <div class="row" id="chkpay">
          <!-- вставляю через JS -->
        </div>
      </div>
    </div>
  </div>
</div>
JS:
JavaScript
1
2
3
4
5
6
7
8
9
10
$(document).ready(function() {
  $(".nf-subscribe .subscribe-pay-method-box input[name=subscribe-pay-method]").change(function() {
    $(".label-subscribe-pay-method").removeClass("selected");
    $(this).parent().addClass("selected");
  });
  
  var chkpayElement = $('#chkpay');
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-3" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-3" value="3"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Онлайн</div></div></div></label></div>'));
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-4" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-4" value="4"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Наличные</div></div></div></label></div>'));
});
0
380 / 230 / 115
Регистрация: 22.11.2016
Сообщений: 379
25.12.2019, 19:09
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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
    <style type="text/css">
        .nf-subscribe .subscribe-pay-method-box .main-title-pay {
  font-weight: bold;
  font-size: 16px;
  color: #2C2C2C;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method {
  display: block;
  -webkit-box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
          box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
  border-radius: 4px;
  padding: 0;
  margin: 0;
  cursor: pointer;
  background: #ffffff;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method:hover {
  -webkit-box-shadow: inset 2px 0 0 #004FC5, inset 0 2px 0 #004FC5, inset 0 -2px 0 #004FC5, inset -2px 0 0 #004FC5;
          box-shadow: inset 2px 0 0 #004FC5, inset 0 2px 0 #004FC5, inset 0 -2px 0 #004FC5, inset -2px 0 0 #004FC5;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .content-box {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
      -ms-flex-direction: row;
          flex-direction: row;
  padding: 11px 15px;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .dot {
  position: absolute;
  display: block;
  width: 12px;
  height: 12px;
  background: #ffffff;
  border-radius: 50%;
  border: 1px solid #004FC5;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .title-box {
  padding-left: 25px;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .title-box .title {
  color: #444444;
  font-size: 16px;
  line-height: 24px;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method .title-box .subtitle {
  font-size: 13px;
  line-height: 18px;
  color: #444444;
}
 
.nf-subscribe .subscribe-pay-method-box .label-subscribe-pay-method input {
  display: none;
}
 
.nf-subscribe .subscribe-pay-method-box .selected {
  background-color: #E2E4E6;
  -webkit-box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
          box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
}
 
.nf-subscribe .subscribe-pay-method-box .selected:hover {
  -webkit-box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
          box-shadow: inset 1px 0 0 #CFCFCF, inset 0 1px 0 #CFCFCF, inset 0 -1px 0 #CFCFCF, inset -1px 0 0 #CFCFCF;
}
 
.nf-subscribe .subscribe-pay-method-box .selected .dot {
  background: #004FC5;
  -webkit-box-shadow: inset 2px 0 0 #ffffff, inset 0 2px 0 #ffffff, inset 0 -2px 0 #ffffff, inset -2px 0 0 #ffffff;
          box-shadow: inset 2px 0 0 #ffffff, inset 0 2px 0 #ffffff, inset 0 -2px 0 #ffffff, inset -2px 0 0 #ffffff;
}
    </style>
</head>
<body>
    <div class="container">
  <div class="nf-subscribe">
    <div class="row pt-4 subscribe-pay-method-box">
      <div class="col-12">
        <div class="main-title-pay">
          Выбирите способ оплаты:
        </div>
      </div>
      <div class="col-12 col-lg-6">
        <label for="pay-method-1" class="label-subscribe-pay-method">
          <input type="radio" name="subscribe-pay-method" id="pay-method-1" value="1" />
          <div class="content-box">
            <div class="dot"></div>
            <div class="title-box">
              <div class="title">Онлайн</div>
            </div>
          </div>
        </label>
      </div>
      <div class="col-12 col-lg-6">
        <label for="pay-method-2" class="label-subscribe-pay-method">
          <input type="radio" name="subscribe-pay-method" id="pay-method-2" value="2" />
          <div class="content-box">
            <div class="dot"></div>
            <div class="title-box">
              <div class="title">Наличными</div>
            </div>
          </div>
        </label>
      </div>
    </div>
  </div>
</div>
 
    <script type="text/javascript">
        "use strict";
 
        $(document).ready(function() {
            let container = $(".container");
 
            container.append($(`
                    <div class="nf-subscribe">
                        <div class="row pt-4 subscribe-pay-method-box">
                          <div class="col-12">
                            <div class="main-title-pay">
                              Выбирите что-то:
                            </div>
                          </div>
                          <div class="col-12 col-lg-6">
                            <label for="pay-method-14" class="label-subscribe-pay-method">
                              <input type="radio" name="subscribe-pay-method13" id="pay-method-14" value="1" />
                              <div class="content-box">
                                <div class="dot"></div>
                                <div class="title-box">
                                  <div class="title">Что-то</div>
                                </div>
                              </div>
                            </label>
                          </div>
                          <div class="col-12 col-lg-6">
                            <label for="pay-method-215" class="label-subscribe-pay-method">
                              <input type="radio" name="subscribe-pay-method13" id="pay-method-215" value="2" />
                              <div class="content-box">
                                <div class="dot"></div>
                                <div class="title-box">
                                  <div class="title">Что-то</div>
                                </div>
                              </div>
                            </label>
                          </div>
                        </div>
                      </div>
                `));
 
            container.append($(`
                    <div class="nf-subscribe">
                        <div class="row pt-4 subscribe-pay-method-box">
                          <div class="col-12">
                            <div class="main-title-pay">
                              Выбирите что-то:
                            </div>
                          </div>
                          <div class="col-12 col-lg-6">
                            <label for="pay-method-113" class="label-subscribe-pay-method">
                              <input type="radio" name="subscribe-pay-method14" id="pay-method-113" value="1" />
                              <div class="content-box">
                                <div class="dot"></div>
                                <div class="title-box">
                                  <div class="title">Что-то2</div>
                                </div>
                              </div>
                            </label>
                          </div>
                          <div class="col-12 col-lg-6">
                            <label for="pay-method-222" class="label-subscribe-pay-method">
                              <input type="radio" name="subscribe-pay-method14" id="pay-method-222" value="2" />
                              <div class="content-box">
                                <div class="dot"></div>
                                <div class="title-box">
                                  <div class="title">Что-то2</div>
                                </div>
                              </div>
                            </label>
                          </div>
                        </div>
                      </div>
                `));
 
            
                $(".nf-subscribe input").each((i, el) => {
                    $(el).change(() => {
                        $(el).closest(".nf-subscribe").find(".label-subscribe-pay-method").removeClass("selected");
                        $(el).parent().addClass("selected")
                    });
                });
 
        });
            
    </script>
</body>
</html>
1
Эксперт JS
6496 / 3907 / 2006
Регистрация: 14.06.2018
Сообщений: 6,781
25.12.2019, 19:34
Лучший ответ Сообщение было отмечено KrisWeb как решение

Решение

JavaScript
1
2
3
4
5
6
7
8
9
10
11
$(document).ready(function() {
 // Обработчики надо вешать потом ))
  var chkpayElement = $('#chkpay');
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-3" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-3" value="3"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Онлайн</div></div></div></label></div>'));
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-4" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-4" value="4"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Наличные</div></div></div></label></div>'));
 
  $(".nf-subscribe .subscribe-pay-method-box input[name=subscribe-pay-method]").change(function() {
    $(".label-subscribe-pay-method").removeClass("selected");
    $(this).parent().addClass("selected");
  });
});
1
the hardway first
Эксперт JS
 Аватар для j2FunOnly
2475 / 1847 / 910
Регистрация: 05.06.2015
Сообщений: 3,610
26.12.2019, 08:39
Цитата Сообщение от KrisWeb Посмотреть сообщение
почему не работают события на элементах, которые я вставляю в страницу через JS?
Потому что не знаете матчасть https://api.jquery.com/on/
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on().
Почитайте, там делов-то на 15 минут.
1
1 / 1 / 1
Регистрация: 15.10.2019
Сообщений: 54
26.12.2019, 10:00  [ТС]
Цитата Сообщение от amr-now Посмотреть сообщение
JavaScript
1
2
3
4
5
6
7
8
9
10
11
$(document).ready(function() {
 // Обработчики надо вешать потом ))
  var chkpayElement = $('#chkpay');
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-3" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-3" value="3"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Онлайн</div></div></div></label></div>'));
  chkpayElement.append($('<div class="col-12 col-lg-6"><label for="pay-method-4" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="pay-method-4" value="4"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">Наличные</div></div></div></label></div>'));
 
  $(".nf-subscribe .subscribe-pay-method-box input[name=subscribe-pay-method]").change(function() {
    $(".label-subscribe-pay-method").removeClass("selected");
    $(this).parent().addClass("selected");
  });
});
блиииин я же пробовала, но почему-то не работало. наверно codepen затупил в тот момент. спасибо))) я уж думала что что-то упустила.

Добавлено через 21 минуту
Цитата Сообщение от amr-now Посмотреть сообщение
JavaScript
1
 // Обработчики надо вешать потом ))
а почему в этом случае не работает? я же вешаю обработчик потом.


JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
$(document).ready(function() {
    
  var chkpayElement = $('#chkpay');
    $.getJSON('http://127.0.0.1:5500/payment.json', function (data) {
        $.each(data.paymentMethods, function (key, entry) {
            chkpayElement.append($('<div class="col-12 col-lg-6"><label for="method' + entry.id + '" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="method' + entry.id + '" value="' + entry.id + '"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">' + entry.name + '</div></div></div></label></div>'));
        })
    });
  $(".nf-subscribe .subscribe-pay-method-box input[name=subscribe-pay-method]").change(function() {
    $(".label-subscribe-pay-method").removeClass("selected");
    $(this).parent().addClass("selected");
  });
});
содержимое json
Кликните здесь для просмотра всего текста
JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "success": true,
  "paymentMethods": [
    {
      "id": 3,
      "name": "Онлайн",
      "enabled": true
    },
    {
      "id": 1,
      "name": "Наличными",
      "enabled": true
    }
  ]
}


Добавлено через 4 минуты
поместила обработчик в функцию, и всё заработало. почему так? вкратце можете пояснить?

JavaScript
1
2
3
4
5
6
7
8
9
10
var chkpayElement = $('#chkpay');
    $.getJSON('payment.json', function (data) {
        $.each(data.paymentMethods, function (key, entry) {
            chkpayElement.append($('<div class="col-12 col-lg-6"><label for="method' + entry.id + '" class="label-subscribe-pay-method"><input type="radio" name="subscribe-pay-method" id="method' + entry.id + '" value="' + entry.id + '"/><div class="content-box"><div class="dot"></div><div class="title-box"><div class="title">' + entry.name + '</div></div></div></label></div>'));
        })
        $(".nf-subscribe .subscribe-pay-method-box input[name=subscribe-pay-method]").change(function() {
            $(".label-subscribe-pay-method").removeClass("selected");
            $(this).parent().addClass("selected");
        });
    });
0
Эксперт JS
6496 / 3907 / 2006
Регистрация: 14.06.2018
Сообщений: 6,781
26.12.2019, 10:35
Цитата Сообщение от KrisWeb Посмотреть сообщение
вкратце можете пояснить?
Потому что функция function (data) { будет запущена строго после завершения функции в параметре .ready(function() {

$.getJSON( означает "получить весточку когда-нибудь потом, а не прям щас". За это время в первую очередь полностью выполнится вся фукция, в которой инструкция $.getJSON.
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
26.12.2019, 10:35
Помогаю со студенческими работами здесь

Событие по клику внутри элемента
Всем привет! Есть JS: //Здесь по клику передаётся id элемента в обработчик redact.php и данные появляются в скрытом div(который...

Почему не работает событие Workbook_WindowDeactivate?
Добрый день! пытаюсь добавить событие, которое срабатывает, если окно рабочей книги не активно: Sub Workbook_WindowDeactivate(ByValWn...

Почему событие KeyDown не работает на форме?
После нажатия на кнопку на форме, она там например изменяет размер формы, Я ХОЧУ нажать на CTRL+X и на событии KEYDOWN!!! Впечатан КОД...

Почему не работает событие MouseLeave и MouseEnter?
Хотел сделать событие при наведении курсора на картинку , но что то делаю не так ) unit Unit3; interface uses ...

Событие по клику
Есть код который создает groupBox в нем linklabel for (int i = 0; i &lt; 6; i++) { groupBox = new...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru