colorbox and preventdefault not working together?

2019-08-25 08:51发布

问题:

I'm calling a colorbox using jquery and trying to prevent the address from changing but it seems to trigger an address change every time. Here is my current code:

<div style='display:none'>
    <div id='send_alert_div' class="wysiwyg_container">
        <h2>Contact Us</h2>
        ....
    </div>
</div>

<a class="contact" href="#" >Contact</a>

my javascript code to handle the click event for Contact

$(".contact").click(function(e){
    e.preventDefault();
    $(".contact").colorbox({width:"600px", height: "420px", inline:true, href:"#send_alert_div"});
});  

Does anyone see why this wouldn't work? It triggers an address change every time it's clicked.

回答1:

I don't know what you are talking about with address changes. That must be controlled by some piece of script that you haven't included. Furthermore, colorbox already applies e.preventDefault(); So you could simplify the above code to simply this:

$(".contact").colorbox({width:"600px", height: "420px", inline:true, href:"#send_alert_div"});

Your other issue sounds unrelated. It's going to be difficult to instruct you on what to do without seeing what code is causing your 'address change', but if it is a simple event binding, you may be able to prevent it by replacing your above code with the following:

$(".contact").unbind('click').colorbox({width:"600px", height: "420px", inline:true, href:"#send_alert_div"});