У меня есть массив, который я повторяю, чтобы поместить текст в отдельные элементы div на веб-странице (позже я анимирую элементы div). Я хочу добавить щелчок к каждому div, поэтому при нажатии на div/текст изменяется вес шрифта. Я знаю по крайней мере один способ использовать onclick в более простой ситуации:
<div class="nameDiv" id="div1" onclick='boldText(this, this.id);'>Test</div>
<script>
function boldText(txt, txtid){
var el = document.getElementById(txtid);
var fontstyle = window.getComputedStyle(el, null).fontWeight;
if (fontstyle != '800') {
txt.style.fontWeight = '800';
} else {
txt.style.fontWeight = '300';
}
}
</script>
Однако я не могу заставить этот же тип работы работать в моем коде с итерацией.
var setNames = function() {
var h = 0;
for(var n = 0; n < numberStudents; n++){
var divName = "floatName" + n;
var names = nameArray[n].fields.nickname; <!-- gets the text/name for each div -->
var divTag = document.createElement('div');
divTag.id = divName;
divTag.innerHTML = names;
divTag.className = "randomFloat";
// try to give each div an onclick
divTag.onclick = boldText(this, this.id);
studentCol.appendChild(divTag); <!-- attach to studentCol/'anchor'/parent element -->
};
};
setNames();
function boldText(txt, txtid){ <!-- pass both the object and the object id -->
var el = document.getElementById(txtid);
// I've tried both lines below -->
var fontstyle = window.getComputedStyle(el, null).fontWeight; <!-- gives me an error saying el is not an object -->
//var fontstyle = window.getComputedStyle(el, null).fontWeight;
// line above gives TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element -->
if (fontstyle != '300') {
txt.style.fontWeight = '300';
} else {
txt.style.fontWeight = '800';
}
};
Возможно ли, что каждый divTag.id может иметь отдельный клик? Если да, то что мне нужно изменить в моем коде?
this
, так иthis.id
? Если вы просто передадитеthis
, функция может использоватьtxt.id
для получения идентификатора, если он ей нужен. - person Barmar   schedule 13.08.2018getElementById
, так как элемент тот же, что иtxt
. - person Barmar   schedule 13.08.2018