开发者

Allow clicking a link through a div that is bound to the "click" event

I have a div containing some content, in which there are some links. The div itself watches for the click event so it can make the content editable. However, I want the user to be able to click the links inside of the div and have it navigate to the linked page rather than edit the content (clicking anywhere else in the div should edit the content though). How do I achieve this?

Code example:

<div id="content">
    Here's a <a href="http://google.com">link</a>.
</div>

// jQuery Javascript:
$("#content").click(function() {
    // Make content editable
});

(Clicking on the link shouldn't make the content editable, and instead should direct the page to google.com.)

Edit: I'm 开发者_JAVA技巧using my own code to make the content editable (switching out the div with a text area, that sort of thing).


Check the event target and return true

$("#content").click(function(e) {
    if ($(e.target).is('a')) {
        return true;
    }
});

Not tested

The thinking behind this is to bail-out early from the handler and, by returning true, allow the browser to handle the event the usual way.


One error you have is that you are using content as a class in your HTML, but as an ID in your jQuery. So you should change your HTML to id="content" (assuming no other elements on your page already have that id.

Your Javascript can look like:

$("#content").click(function(){
    this.setAttribute('contenteditable', 'true');
    $(this).focus();
}).blur(function(){
    this.setAttribute('contenteditable', 'false'); 
});

$("#content a").click(function(e){
    e.stopPropagation();
});

Here's a JSFiddle: http://jsfiddle.net/q77Bs/


example

use event.stopPropagation()

// jQuery Javascript:
$(".content").click(function(e) {
    // make content editable
});

$('.content a').click(function(e) {
    e.stopPropagation();
});


You could change the z-index of the link to be greater than that of the div (not sure if that will work), or you can place each link inside another div with a higher zindex than the main div. This will prevent clicks from registering on the primary div, so make sure the secondary divs are correctly sized so as not to prevent the editing functionality


$('#content a ').live("click", function(event){
   event.stopPropagation();
});

this will do the trick

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜