尝试使用变量减少 JavaScript 的重复
我正在尝试减少代码中的重复,但没有任何运气。我将代码简化为最简单的功能,以尝试使其正常工作。
这个想法是采用 id 名称的最后两个字母,因为这些字母与先前声明的变量相同,并用它来引用旧变量。
我使用警报来测试我是否获得了正确的输出,并弹出警报窗口,显示“E1”。所以我不太确定为什么当我尝试使用它时它不起作用。
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).addClass('active');
});
当我使用原始变量 E1 而不是 fileName 时,代码块有效。我想使用 fileName ,因为我希望此函数适用于单击时的多个元素,而不是对每个元素重复该函数。
我怎样才能做到这一点?我缺少什么?
谢谢。
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).addClass('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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fileName
仍然是一个字符串。 JavaScript 不知道您想要使用同名的变量。您正在对字符串调用play()
方法,该字符串当然不存在(因此您会收到错误)。建议:
将对象存储在表中:
另一个建议:
不要使用 ID 来保存有关文件的信息,而是考虑使用 HTML5
data
属性:然后您可以通过以下方式获取名称:
这使您的代码更加灵活。您不依赖于为元素提供特定格式的 ID。
fileName
is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling theplay()
method on a string, which of course does not exist (hence you get an error).Suggestion:
Store your objects in a table:
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5
data
attributes:Then you can get the name with:
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.