如何动态传递元素id并调用javascript函数?
我有如下所示的 javascript 代码 -
function initPage(){
// Left Navigation Pane - moverOver effect:
document.getElementById("imgHowToBuy").onmouseover = leftNavHoverIn;
document.getElementById("imgNewAddition").onmouseover = leftNavHoverIn;
document.getElementById("imgMostPopular").onmouseover = leftNavHoverIn;
document.getElementById("imgOffer").onmouseover = leftNavHoverIn;
document.getElementById("imgRecentlySold").onmouseover = leftNavHoverIn;
.....
}
基本上我的代码可以工作(该函数被调用并执行得很好)。但我不认为我在这里使用了最佳实践的原则。不断调用同一个函数看起来有点奇怪;我可以以某种方式传递元素的 id 作为参数,然后执行该函数,以便整个事情减少到一行代码吗?
我是一个自学的 js 人:D
谢谢!
I have javascript code like below -
function initPage(){
// Left Navigation Pane - moverOver effect:
document.getElementById("imgHowToBuy").onmouseover = leftNavHoverIn;
document.getElementById("imgNewAddition").onmouseover = leftNavHoverIn;
document.getElementById("imgMostPopular").onmouseover = leftNavHoverIn;
document.getElementById("imgOffer").onmouseover = leftNavHoverIn;
document.getElementById("imgRecentlySold").onmouseover = leftNavHoverIn;
.....
}
Basically my code works (the function gets called and executes beautifully). But I dont think I am using the principles of best practice here. It looks a little wierd to keep calling the same function; can i somehow pass the id of the element as the argument, and then execute the function, so that this whole thing reduces to a single line of code?
I'm a self taught js guy :D
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不是“调用相同的函数”,您只是将单个函数分配给页面上的许多元素。我认为这里没有什么特别错误的地方。
您可以存储要分配此函数的所有元素的 id,这将减少代码行数,但没有具体原因这样做。
You're not "calling the same function", you're simply assigning a single function to lots of elements on a page. I see nothing specifically wrong here.
You could store the id's of all the elements you want to assign this function to, which would reduce the number of lines of code, but there's no specific reason to do so.
您可以这样做:
您还可以将元素 ID 作为数组传递,并循环遍历函数内的数组,这会将其减少为一行(可见)代码:
最佳实践需要更多检查/验证但以上内容应该有所帮助。
You could do something like this:
You could also pass in the element IDs as an array and loop through the array inside the function, which would reduce it to one line of (visible) code:
More checking / validation would be required for best practice but the above should help.
试试这个:
Try this: