简体   繁体   English

单击事件侦听器后如何传递ID以起作用

[英]How to pass ID to function after event listener click

Im pretty new to HTML5/Javascript/CSS3 and im confused on exactly how to pass the id of my event listener to the new function. 我对HTML5 / Javascript / CSS3还是很陌生,并且对如何将事件侦听器的ID传递给新函数感到困惑。 I'm building a video player and this is the volume up and down part, and I would rather be able to use one function for both volume up and volume down using if statements, which would check the id. 我正在构建一个视频播放器,这是调高音量和调低音量的部分,我宁愿能够使用if语句使用一个函数来调高音量和调低音量,这将检查ID。

Here is what im working with: 这是我正在使用的:

 volume_up = document.getElementById('volume_up'); //get the volume_up button
 volume_up.addEventListener('click', volumeUp, false); //call function "volumeUp" on click

Here is the "volumeUp" function: 这是“ volumeUp”功能:

function volumeUp(click_button){
alert(click_button.id); // i want to be able to get the id here
myMovie.volume = myMovie.volume - 0.1;
}

If i was able to get the ID, i could do vol up and vol down in this one function instead of 2 via if statements. 如果我能够获得ID,则可以通过if语句在此函数中上下调卷而不是2。

I have tried doing this: 我尝试这样做:

   volume_up.addEventListener('click', volumeUp(volume_up), false);

and

    volume_up.addEventListener('click', volumeUp(volume_up.id), false);

with no luck. 没有运气。 I have the volume up button linked up, and whenever i press it, the volume does change, and the alert does popup, but it says undefined. 我将音量调高按钮链接起来,每当我按下它时,音量确实会发生变化,并且警报也会弹出,但是它显示未定义。

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks :) 谢谢 :)

document.getElementById('volume_up').addEventListener('click', _volume, false);
document.getElementById('volume_down').addEventListener('click', _volume, false);

function _volume(event){
    if(this.id == 'volume_up') {
        myMovie.volume += 0.1;
    } else {
        myMovie.volume -= 0.1;
    }
}

This is just an example. 这只是一个例子。 You'll want to use some defensive logic to check for IE and use attachEvent instead when applicable. 您将需要使用一些防御性逻辑来检查IE,并在适用时改用attachEvent

The reason these didn't work... 这些不起作用的原因...

volume_up.addEventListener('click', volumeUp(volume_up), false);
volume_up.addEventListener('click', volumeUp(volume_up.id), false);

...is because you're invoking the function and passing the result of volumeUp as the callback, which would not be a typeof == 'function' ...是因为您正在调用该函数,并将volumeUp结果作为回调传递,这不是typeof == 'function'

In the event handler "this" is bound to the element that fired the event, so you can just use "this.id". 在事件处理程序中,“ this”绑定到触发事件的元素,因此您可以仅使用“ this.id”。

Check out this example: http://jsfiddle.net/vyGdJ/ 看看这个例子: http : //jsfiddle.net/vyGdJ/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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