简体   繁体   中英

How do I make an object constructor that assigns a key value pair with an onclick function

I am trying to make a friend a soundboard application. The UI would have a 4 x 5 (or more) grid system of various faces in a .png format that once tapped on, would play an audio file.

I am not sure how to make an object constructor that gives an object an onclick function with an assigned sound file.

My goal is to use my makeNewFace() function to build an object, give it an image value, a sound file value, and an automatic onclick functionality to play said sound file.

Finally, I want to push that object to my faceArray that will automatically show up on my index.html file as a .png face with the assigned onclick function to play its matching sound file.

I hope I make sense.

//objects array with an image, sound, and string saying

faceArray = [

{ image: 'numbaniFace.png',
  sound: 'numbaniSaying.mp3',
  saying: 'Nooombaniii'
},

{ image: 'stanfordFace.png',
  sound: 'stanfordSaying.mp3',
  saying: 'Stanford Alumni'
}
];


function makeNewFace(image, sound, saying){
    this.image = image;
    this.sound = sound;
    this.saying = saying;

    var newImg = document.createElement('img');
    newImg.setAttribute('src', image);
    newImg.setAttribute('onclick', playSound(sound));
}

function playSound(){
    //????
}

You might probably try to make it like

 function MakeNewFace(img, snd, saying){ this.image = img; this.sound = new Audio(snd); this.saying = saying; this.newImg = document.createElement('img'); this.newImg.setAttribute('src', this.image); this.newImg.addEventListener("click", this.sound.play.bind(this.sound)); } var face = new MakeNewFace("http://metiscappadociatours.com/wp-content/uploads/2015/10/butterfly-balloons1.jpg","http://www.vibrationdata.com/Petrov_D.mp3","hey..!"), myDiv = document.getElementById("myDiv"); myDiv.appendChild(face.newImg); 
 img { margin: 0 5% 0; max-width: 90%; max-height: 100%; } 
 <div id="myDiv"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM