开发者

Prevent default on a click within a JQuery tabs in Google Chrome

开发者 https://www.devze.com 2023-01-02 05:13 出处:网络
I would like to prevent the default behaviour of a click on a link. I tried the return false; also javascript:void(0); in the href attribute but it doesn’t seem to work. It works fine in Firefox, but

I would like to prevent the default behaviour of a click on a link. I tried the return false; also javascript:void(0); in the href attribute but it doesn’t seem to work. It works fine in Firefox, but not in Chrome and IE.

I have a single tab that loads via AJAX the content which is a simple link.

<script type="text/javascript">
        $(function() {
            $("#tabs").tabs({
                ajaxOptions: {
                    error: function(xhr, status, index, anchor) {
                        $(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. If this wouldn't be a demo.");
                    },
                    success: function() {
                        alert('hello');
                        $('#lk').click(function(event) {
                            alert('Click Me');
                            event.preventDefault();
                            return false;
                        });
开发者_如何学Go                    }
                },
            load: function(event, ui) {
                    $('a', ui.panel).click(function(event) {
                        $(ui.panel).load(this.href);
                        event.preventDefault();
                        return false;
                    });
                }           
            });
        });
</script>
<body>
      <div id="tabs">
        <ul>
            <li><a href="linkChild.htm">Link</a></li> 
        </ul>
      </div>
</body>

The content of linkChild.htm is

<a href="http://www.google.com" id="lk">Click Me</a>

So basically when the tab content is loaded with success, a click event is attached to the link “lk”. When I click on the link, the alert is displayed but then link disappears. I check the HTML and the element is actually removed from the DOM.


$('#selector').click(function(event) { 

    event.preventDefault();

});

The event object is passed to your click handler by default - you have to have something there to receive it. Once you have the event, you can use jQuery's .preventDefault() method to cancel the link's behavior.

Edit:

Here's the fragment of your code, corrected:

$('a', ui.panel).click(function(event) {
   $(ui.panel).load(this.href);
   event.preventDefault(); 
   return false;
});

Notice the addition of the word 'event' when creating the anon function (or you could use just e, or anything else - the name is unimportant, the fact there's a var there is.

0

精彩评论

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