开发者

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.

The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.

I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.

E1 = new Audio('audio/E1.ogg');

$('#noteE1').click(function() {
    var fileName = this.id.slice(4);
    //alert(fileName); used to test output
    fileName.play();
    $('#note' + fileName).a开发者_StackOverflow社区ddClass('active');
});

The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.

How can I make this work? What am I missing?

Thanks.


fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).

Suggestion:

Store your objects in a table:

var files = {
    E1: new Audio('audio/E1.ogg')
};

$('#noteE1').click(function() {
    var fileName = this.id.slice(4);
    //alert(fileName); used to test output
    files[fileName].play();
    $('#note' + fileName).addClass('active');
});

Another suggestion:

Instead of using the ID to hold information about the file, consider using HTML5 data attributes:

<div id="#note" data-filename="E1">Something</div>

Then you can get the name with:

var filename = $('#note').data('filename');

This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜