开发者

Fire next event up, but not after that

For a page, I've been given a link wrapped inside a label, like this:

<label for='checkbox_elem'>
    Links to <a href='somepage.php' target='anotherwindow'>another page.</a>
</label>

When the user clicks on the link in all browser, the page is spawned in a new tab as envisioned, but in Firefox the checkbox linked to the label is also selected. This is a non-desired behavior.

I want to run some jQuery to allow the link to pop, but to kill the event thereafter. I have the following, which works, but isn't very elegant:

$(document).ready(function(){
    $('label a').click(function(e){
        open($(this).attr('href'), $(this).attr('target'));
        return false;
    });
});

Can any of you think of a more elegant way to do this than to replicate the element's behavior manually and kill the event?


As an aside, I've been trying with stopPropagation, but haven't had much success.

Also, please note that the above solution does work, but I am looking for something more elegant for generically stopping events from propagating past their first 开发者_JAVA技巧call. (The first native call. If I add a callback, I still want the native element behavior to fire, but not that of its parent) .


Try stopping the event from propagating at the label.

$(document).ready(function(){
    $('label').click(function(e){
        e.stopPropagation();
    });
});


You could use $(elem).one(fn) -- http://api.jquery.com/one/


Maybe you should change your html to:

<label for='checkbox_elem'>Links to </label>
<a href='somepage.php' target='anotherwindow'>another page.</a>

and use no javascript at all?


This one:

<label> test <a href="#">Test</a> <input type="checkbox" name="check[]" /></label>

Or even:

<label for="test1"> test <a href="#">Test</a> <input type="checkbox" name="test1" id="test1" class="checkbox" /></label>

And js:

$('a').click(function(e){
    var t=$(this);
    window.open(t.attr('href'), t.attr('target'));
    return false;
});

Works for me. Maybe there is smth that interfere with your script?


Well, if you are allowed to change the html on client-side, you can always move the links outside the label like this,

$(document).ready(function(){ 
    $('label').find('a').each(function(){
        var $anchor = $(this);        
        $(this).closest('label').after($anchor);
    });
});​

demo


KISS

$(document).ready(function(){
    $('label a').click(function(e){
        open($(this).attr('href'), $(this).attr('target'));
        $(this).parent().click(); //Click the label again to reverse the effects of the first click.
        return false;
    });
});


Try using .one() instead of .click():

$(document).ready(function(){
    $('label a').one(function(e){
        open($(this).attr('href'), $(this).attr('target'));
        return false;
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜