Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javascript - how to disable or enable all onClick for images on a page

When the user clicks on an image, I want the onClicks on all other images to be disabled until my function has finished.

I currently have this code that disables them:

var eles = document.getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
   eles[i].onclick = false;

but I'm not sure how to re enable them. I have tried:

var eles = document.getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
   eles[i].onclick = true;

But its not working. anyone have solution for this problem

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your solution doesn't work because you removed your onClick with onClick = false. After that you need to create the onClick event handler again.

This is probably your way of adding onclick events, I changed it so it should work.

<img src="image1.jpg" onclick="when_i_click();"/>
<img src="image2.jpg" onclick="when_i_click();"/>

Try adding a function to your onclick as above.

Your onclick function:

var when_i_click = function(){
    alert('image clicked!');
}

This is how you disable your onclicks (your method)

var eles = document.getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
   eles[i].onclick = null;

This is how you re-enable them (re-attach function to onClick )

var eles = document.getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
   eles[i].onclick = when_i_click;

This is a Jquery solution jquery:

Try using unobstructive javascript, by not adding onclick event handlers in the DOM.

<script>
(function(){
    var function_is_finished = false;
    $('img').on('click',function(event){
        if(function_is_finished) {
            //Do your stuff when someone clicks on Img
        }
    });
})();
</script>

When your function is finished just set function_is_finished to true


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...