开发者

Jquery - infinite loop

I have a webpage which has a button placed inside a div. What i want to achieve is when users click on the div, it would trigger the button inside clicked. The code is something like:

<div id='main'>     
 <input id="button" type="button" onclick="javascript:dosomething();"  value="submit" />
</div>


<script type="text/javascript">
    $(function(){
     $('#main').bind('click', function(){
      $('#button').trigger('click');
     })
    })
</script>

When executed (click on the div), it would throw javascript error "too much recursion". It kinda makes sense why its infinite loop there but I'm not sure what is the right way to achieve this action? (plz dont ask me why i want it that way, its not my 开发者_如何学JAVAcode!)

thanks for your kindy help!


Stop event bubbling inside the button click event handler.

Use e.stopPropagation()

If you are using jquery then make all event handlers in jquery way. So the button click will be

$('#button').click(function(e){
    doSomething();
    e.stopPropagation();
});

So the whole thing will be

$(function(){ 
    $('#main').bind('click', function(){ 
        $('#button').trigger('click'); 
    });

    $('#button').click(function(e){
        doSomething();
        e.stopPropagation();
    });

});


$("#main").on('click', function (e) {
    e.stopPropagation();
    $("#button")[0].click();
});

Its work for me

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜