ฉันมีอาร์เรย์ที่ฉันวนซ้ำเพื่อวางข้อความใน div แยกกันบนหน้าเว็บ (ต่อมาฉันจะทำให้ div เคลื่อนไหว) ฉันต้องการเพิ่ม onclick ลงในแต่ละ 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 สามารถมี onclick แยกกันได้ หากเป็นเช่นนั้น ฉันจะต้องเปลี่ยนแปลงอะไรบ้างในรหัสของฉัน
this
และthis.id
ไปยังฟังก์ชัน หากคุณเพิ่งผ่านthis
ฟังก์ชันจะสามารถใช้txt.id
เพื่อรับ ID ได้หากต้องการ - person Barmar   schedule 13.08.2018getElementById
เนื่องจากองค์ประกอบจะเหมือนกับtxt
- person Barmar   schedule 13.08.2018