简体   繁体   English

Javascript onFocus。 然后 onClick 里面 function

[英]Javascript onFocus . then onClick inside function

I'm trying to make it so when an element gets focus it calls a function which then will take care of all other events - here is my code for now.我正在努力做到这一点,所以当一个元素获得焦点时,它会调用 function ,然后它将处理所有其他事件 - 这是我现在的代码。

<span id="checkbox" class="checkbox" onFocus="cbHover(checkbox)"></span>

<script type="text/javascript">
    function cbHover(id) {
        if(document.getElementById(id).onClick) {
            document.getElementById(id).style.backgroundPositionY = '-63px';
        }
    }
</script>

Obviously this isn't working:( So is there a way to keep the function running to listen for other events?显然这不起作用:(那么有没有办法让 function 运行以监听其他事件?

Thanks!谢谢!

When the object is clicked, it is already focused.当点击 object 时,它已经被聚焦。 You can either skip the onFocus and replace it with onClick, or the other way around and remove if(document.getElementById(id).onClick) from the code, because you don't need it.您可以跳过 onFocus 并将其替换为 onClick,或者反过来并从代码中删除if(document.getElementById(id).onClick) ,因为您不需要它。

You are able to use two events: onFocus and onLostFocus.您可以使用两个事件:onFocus 和 onLostFocus。 In onFocus event handler you are able to add onClick event to element:在 onFocus 事件处理程序中,您可以将 onClick 事件添加到元素:

document.getElementById(id).addEventListener('click',function_name,true);

In onLostFocus event handler you are able to remove event在 onLostFocus 事件处理程序中,您可以删除事件

document.getElementById(id).removeEventListener('click',function_name,true)

this is a bad idea even if you did get it to work you run the risk of applying multiple clicks on the same element.这是一个坏主意,即使你确实让它工作了,你也会冒着在同一个元素上应用多次点击的风险。 your best bet it to just apply the click event on dom ready I typically use jQuery你最好的选择是在 dom ready 上应用点击事件我通常使用 jQuery

so if I where doing this in jquery i would do it like this所以如果我在 jquery 中这样做,我会这样做

$(document).ready(function(){
    $('.classname').click(function(){
       // what to do onclick
    });
});

The reason it isnt working is the parameter that is passed, should be enclosed in quotes.它不起作用的原因是传递的参数,应该用引号引起来。

It should be它应该是

onFocus="cbHover('checkbox')"

otherwise, javascript treats checkbox as a variable and tries to pass the value of the variable which is null.否则,javascript 将复选框视为变量并尝试传递变量的值 null。

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

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