จะใช้ onlick เพื่อเปลี่ยนแบบอักษรในอาร์เรย์ div ซ้ำได้อย่างไร

ฉันมีอาร์เรย์ที่ฉันวนซ้ำเพื่อวางข้อความใน 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 แยกกันได้ หากเป็นเช่นนั้น ฉันจะต้องเปลี่ยนแปลงอะไรบ้างในรหัสของฉัน


person Doug Smith    schedule 13.08.2018    source แหล่งที่มา
comment
ทำไมคุณถึงคิดว่าคุณต้องส่งทั้ง this และ this.id ไปยังฟังก์ชัน หากคุณเพิ่งผ่าน this ฟังก์ชันจะสามารถใช้ txt.id เพื่อรับ ID ได้หากต้องการ   -  person Barmar    schedule 13.08.2018
comment
และไม่จำเป็นต้องเรียก getElementById เนื่องจากองค์ประกอบจะเหมือนกับ txt   -  person Barmar    schedule 13.08.2018


คำตอบ (1)


ปัญหาคือคุณกำลังกำหนดผลลัพธ์ของฟังก์ชัน boldText ไม่ใช่ตัวฟังก์ชันเอง โปรดลองสิ่งนี้:

divTag.onclick = boldText;

ด้วยวิธีนี้คุณสามารถเข้าถึง this ภายในฟังก์ชัน boldText ได้โดยไม่จำเป็นต้องส่งผ่านข้อโต้แย้งใด ๆ เช่น.

this.style.fontWeight = '300';
person Sergii Vorobei    schedule 13.08.2018
comment
ฟังก์ชันสามารถส่งคืนค่าได้หรือไม่? ตัวอย่างเช่น ฟังก์ชันboldText()สามารถส่งคืนค่าที่บันทึกสถานะของน้ำหนักแบบอักษรได้หรือไม่ - person Doug Smith; 14.08.2018